Slim JSON Outputs

前端 未结 17 1666
一整个雨季
一整个雨季 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:47

    I feel your pain. I wanted to make a reusable function, so I made a helpers file, and included this:

    function toJSON($app, $content) {
        $response = $app->response;
        $response['Content-Type'] = 'application/json';
        $response->body( json_encode($content) );
    };
    

    And then I used it like this:

    $app->get('/v1/users/:id', function($id) use ($app)
    {
        //instantiate SMM data model
        $model = new user_model($site);
    
        //get all docs, or one, depending on if query contains a page ID
        $doc = $model->get(array());
    
        //if the object contains main -- we don't need the outer data.
        toJSON($app, $doc);
    });
    

    Edit: I think it would be really nice if there were already functions like this built into the response object for the popular mime types

    0 讨论(0)
  • 2021-01-30 09:47

    You can use in slim3, Slim’s Response object custom method withJson($data, $status, $encodingOptions)

    $app->get('/hello/{name}', function ($request, $response, $args) {
        $data['msg']='Hello '.$request->getAttribute('name');
        $newResponse = $response->withJson($data);
    });
    

    For more information read here.

    0 讨论(0)
  • 2021-01-30 09:49

    [BEFORE]: Content-Type text/html; charset=UTF-8

    Not working with SOAPUI JSON :(

    $this->get('get_all', function ($req, $res, $args) {
        $um = new UserModel();
    
        return $res
           ->withHeader('Content-Type', 'application/json')
           ->getBody()
           ->write(
            json_encode(
                $um->get_all()
            )
        );
    });
    

    [AFTER]: Content-Type application/json;charset=utf-8

    Working with SOAPUI JSON ;)

    $this->get('get_all', function ($req, $res, $args) {
        $um = new UserModel();
    
        return $res
            ->withHeader('Content-type', 'application/json;charset=utf-8')
            ->withJson($um->get_all());
    
    0 讨论(0)
  • 2021-01-30 09:51

    Since everyone has complicated their answers with functions and classes, I'll throw in this simplified answer. The \Slim\Http\Response can do it for you like this:

    $app = new \Slim\Slim();
    
    $app->get('/something', function () use ($app) {
        $response = $app->response();
        $response['Content-Type'] = 'application/json';
        $response->status(200);
        $response->body(json_encode(['data' => []]));
    });
    
    $app->run();
    

    As you're most likely only returning JSON data it might be a good idea to make an appropriate middleware, see http://www.sitepoint.com/best-practices-rest-api-scratch-introduction/.

    0 讨论(0)
  • 2021-01-30 09:52

    Use Slim JSON API https://coderwall.com/p/otcphg/create-a-json-restfull-api-using-slim-framework. You can handle JSON output with it.

    0 讨论(0)
  • 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);
    });
    
    0 讨论(0)
提交回复
热议问题