Mike
Mike

Reputation: 5808

Slim 3 no response

So this is what i had first:

$app->get('/object/{id:[0-9]+}', function ($request, $response, $args) {    
    $id = (int)$args['id'];
    $this->logger->addInfo('Get Object', array('id' => $id));
    $mapper = new ObjectMapper($this->db);
    $object = $mapper->getObjectById($id);
    return $response->withJson((array)$object);
});

It worked well and outputted the whole DB Object as a nice JSON String.

Now i reorganized everything a little on MVC basis and this is whats left:

$app->get('/object/{id:[0-9]+}', ObjectController::class . ':show')->setName('object.show');

It also works, but i don't get any Output. If i put a var_dump before the DB Object is there, but how do i get a JSON String from that again?

Here comes the Controller

<?php
namespace Mycomp\Controllers\Object;

use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
use Interop\Container\ContainerInterface;
use Mycomp\Models\Object;

class ObjectController
{
    protected $validator;
    protected $db;
    protected $auth;
    protected $fractal;

    public function __construct(ContainerInterface $container)
    {
        $this->db = $container->get('db');
        $this->logger = $container->get('logger');
    }

    public function show(Request $request, Response $response, array $args)
    {
        $id = (int)$args['id'];

        $this->logger->addInfo('Get Object', array('id' => $id));

        $object = new Object($this->db);
        return $object->getObjectById($id);
    }
}

Upvotes: 0

Views: 116

Answers (2)

Nima
Nima

Reputation: 3409

In order for Slim to send HTTP response to client, route callback must return some data that Slim understands. That type of data, according to Slim documentation is a PSR 7 Response object.

This is important, because what the route callback returns will not necessarily be sent to client exactly as is . It might be used by middlewares to teak the response before sending it to the client.

the $response object, injected by Slim into your route callbacks is used for that purpose. Slim also provides some helper methods like 'withJson` to generate a proper (PSR 7) JSON response with proper HTTP headers.

So as I said in comment, you need to return response object

public function show(Request $request, Response $response, array $args)
    // Prepare what you want to return and
    // Encode output data as JSON and return a proper response using withJson method  
    return $response->withJson($object->getObjectById($id));
}

Upvotes: 0

Zamrony P. Juhara
Zamrony P. Juhara

Reputation: 5262

As Nima said in comment, you need to return Response object

public function show(Request $request, Response $response, array $args)
    ...  
    return $response->withJson($object->getObjectById($id));
}

Upvotes: 3

Related Questions