Audrey Roberts Audrey Roberts - 1 month ago 8
PHP Question

Slim Framework returning response without 'return $response'

I'm confused with how Slim is returning a response without

return $response
as per the documentation.

If I have the following code:

$app->get('/login', function ($request, $response, $args) {

$response = $this->view->render($response, "login.php");
return $response;
});


When I call
/login
through my browser it renders my
login.php
template, which is what I'd expect.

But if I remove
return $response
it still works
which doesn't seem right?

$app->get('/login', function ($request, $response, $args) {

$response = $this->view->render($response, "login.php");
});


Both sets of code have the same output.

How is Slim showing the response if
$response
is not being returned?

Answer

The body is a Psr\Http\Message\StreamInterface which is not immutable, when you append something to the body you normally do:

$body = $response->getBody();
$body->write($string);
$body->write($string2);

This changes the content of the stream but is still in the same $response-Object.

As the view renderer only appends to the body, there is no need to actually return the $response.