Your Slim app’s routes and middleware are given a PSR 7 response object that represents the current HTTP response to be returned to the client. The response object implements the PSR 7 ResponseInterface with which you can inspect and manipulate the HTTP response status, headers, and body.
The PSR 7 response object is injected into your Slim application routes as the second argument to the route callback like this:
<?php
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\ResponseInterface;
$app = new \Slim\App;
$app->get('/foo', function (ServerRequestInterface $request, ResponseInterface $response) {
// Use the PSR 7 $response object
return $response;
});
$app->run();The PSR 7 response object is injected into your Slim application middleware as the second argument of the middleware callable like this:
<?php
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\ResponseInterface;
$app = new \Slim\App;
$app->add(function (ServerRequestInterface $request, ResponseInterface $response, callable $next) {
// Use the PSR 7 $response object
return $next($request, $response);
});
// Define app routes...
$app->run();Every HTTP response has a numeric status code. The status code
identifies the type of HTTP response to be returned to the client. The PSR 7
Response object’s default status code is 200 (OK). You can get the PSR 7
Response object’s status code with the getStatusCode() method like this.
$status = $response->getStatusCode();You can copy a PSR 7 Response object and assign a new status code like this:
$newResponse = $response->withStatus(302);Every HTTP response has headers. These are metadata that describe the HTTP response but are not visible in the response’s body. Slim’s PSR 7 Response object provides several methods to inspect and manipulate its headers.
You can fetch all HTTP response headers as an associative array with the PSR 7
Response object’s getHeaders() method. The resultant associative array’s keys
are the header names and its values are themselves a numeric array of string
values for their respective header name.
$headers = $response->getHeaders();
foreach ($headers as $name => $values) {
echo $name . ": " . implode(", ", $values);
}You can get a single header’s value(s) with the PSR 7 Response object’s
getHeader($name) method. This returns an array of values for the given header
name. Remember, a single HTTP header may have more than one value!
$headerValueArray = $response->getHeader('Vary');You may also fetch a comma-separated string with all values for a given header
with the PSR 7 Response object’s getHeaderLine($name) method. Unlike the
getHeader($name) method, this method returns a comma-separated string.
$headerValueString = $response->getHeaderLine('Vary');You can test for the presence of a header with the PSR 7 Response object’s
hasHeader($name) method.
if ($response->hasHeader('Vary')) {
// Do something
}You can set a header value with the PSR 7 Response object’s
withHeader($name, $value) method.
$newResponse = $oldResponse->withHeader('Content-type', 'application/json');You can append a header value with the PSR 7 Response object’s
withAddedHeader($name, $value) method.
$newResponse = $oldResponse->withAddedHeader('Allow', 'PUT');withHeader() method, this method appends
the new value to the set of values that already exist for the same header
name. The Response object is immutable. This method returns a
copy of the Response object that has the appended header value.
You can remove a header with the Response object’s withoutHeader($name) method.
$newResponse = $oldResponse->withoutHeader('Allow');An HTTP response typically has a body. Slim provides a PSR 7 Response object with which you can inspect and manipulate the eventual HTTP response’s body.
Just like the PSR 7 Request object, the PSR 7 Response object implements
the body as an instance of \Psr\Http\Message\StreamInterface. You can get
the HTTP response body StreamInterface instance with the PSR 7 Response
object’s getBody() method. The getBody() method is preferable if the
outgoing HTTP response length is unknown or too large for available memory.
$body = $response->getBody();The resultant \Psr\Http\Message\StreamInterface instance provides the following
methods to read from, iterate, and write to its underlying PHP resource.
getSize()tell()eof()isSeekable()seek()rewind()isWritable()write($string)isReadable()read($length)getContents()getMetadata($key = null)Most often, you’ll need to write to the PSR 7 Response object. You can write
content to the StreamInterface instance with its write() method like this:
$body = $response->getBody();
$body->write('Hello');You can also replace the PSR 7 Response object’s body with an entirely new
StreamInterface instance. This is particularly useful when you want to pipe
content from a remote destination (e.g. the filesystem or a remote API) into
the HTTP response. You can replace the PSR 7 Response object’s body with
its withBody(StreamInterface $body) method. Its argument MUST be an
instance of \Psr\Http\Message\StreamInterface.
$newStream = new \GuzzleHttp\Psr7\LazyOpenStream('/path/to/file', 'r');
$newResponse = $oldResponse->withBody($newStream);Slim’s Response object has a custom method withJson($data, $status, $encodingOptions) to help simplify the process of returning JSON data.
The $data parameter contains the data structure you wish returned as JSON. $status is optional, and can be used to return a custom HTTP code. $encodingOptions is optional, and are the same encoding options used for json_encode().
In it’s simplest form, JSON data can be returned with a default 200 HTTP status code.
$data = array('name' => 'Bob', 'age' => 40);
$newResponse = $oldResponse->withJson($data);We can also return JSON data with a custom HTTP status code.
$data = array('name' => 'Rob', 'age' => 40);
$newResponse = $oldResponse->withJson($data, 201);The Content-Type of the Response is automatically set to application/json;charset=utf-8.
If there is a problem encoding the data to JSON, a \RuntimeException($message, $code) is thrown containing the values of json_last_error_msg() as the $message and json_last_error() as the $code.
withJson() was called.