PHP Slim, issue when returning a response

Viewed 3243

I'm trying to return some content using a Response object. These are the interfaces implemented:

use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\Factory\AppFactory;

Then, in a GET function, i create my own JSON, and trying to reurn it as a response:

$app->get('/getpersons', function(Request $request, Response $response, $args){
    $person= new stdClass();

    $person->id = 1;
    $person->name='Name example';
    $person->address = 'Street example';


    return $response->getBody()->write(json_encode($person));
});

But I'm getting the next error:

Return value of Slim\Handlers\Strategies\RequestResponse::__invoke() must
implement interface Psr\Http\Message\ResponseInterface

I don't have any idea what is happening. Any help?

3 Answers

Solved! Must be written like this:

$response->getBody()->write(json_encode($person));
return $response;

You want:

$response->write() 

That method returns the response object. Internally it calls $response->getBody()->write()

According to the Psr\Http\Message\StreamInterface specs, the write() method looks like this:

/**
 * Write data to the stream.
 *
 * @param string $string The string that is to be written.
 * @return int Returns the number of bytes written to the stream.
 * @throws \RuntimeException on failure.
 */
public function write($string);

So it doesn't return the instance, it just returns a byte count. I suspect you were relying on getting some kind of fluent interface.

Related