Slim JSON Outputs

前端 未结 17 1697
一整个雨季
一整个雨季 2021-01-30 09:00

I am using the Slim framework with PHP to create a RESTful API for my app. However, I assumed that the framework would have some way of creating easier JSON outputs rather than

17条回答
  •  遇见更好的自我
    2021-01-30 09:53

    you can extend slim with an output function which output is depending the REST request was called:

    class mySlim extends Slim\Slim {
        function outputArray($data) {
            switch($this->request->headers->get('Accept')) {
                case 'application/json':
                default:
                    $this->response->headers->set('Content-Type', 'application/json');
                    echo json_encode($data);        
            }       
        } 
    }
    
    $app = new mySlim();
    

    and use it like this:

    $app->get('/test/', function() use ($app) {
        $data = array(1,2,3,4);
        $app->outputArray($data);
    });
    

提交回复
热议问题