Response

Your Slim app’s routes and middleware are given a PSR-7 response object thatrepresents the current HTTP response to be returned to the client. The responseobject implements the PSR-7 ResponseInterface with which you caninspect and manipulate the HTTP response status, headers, and body.

How to get the Response object

The PSR-7 response object is injected into your Slim application routes as thesecond argument to the route callback like this:

  1. <?php
  2. use Psr\Http\Message\ResponseInterface as Response;
  3. use Psr\Http\Message\ServerRequestInterface as Request;
  4. use Slim\Factory\AppFactory;
  5. require __DIR__ . '/../vendor/autoload.php';
  6. $app = AppFactory::create();
  7. $app->get('/hello', function (ServerRequest $request, Response $response) {
  8. $response->getBody()->write('Hello World');
  9. return $response;
  10. });
  11. $app->run();
Figure 1: Inject PSR-7 response into application route callback.

The Response Status

Every HTTP response has a numeric status code. The status codeidentifies the type of HTTP response to be returned to the client. The PSR-7Response object’s default status code is 200 (OK). You can get the PSR-7Response object’s status code with the getStatusCode() method like this.

  1. $status = $response->getStatusCode();
Figure 3: Get response status code.

You can copy a PSR-7 Response object and assign a new status code like this:

  1. $newResponse = $response->withStatus(302);
Figure 4: Create response with new status code.

The Response Headers

Every HTTP response has headers. These are metadata that describe the HTTPresponse but are not visible in the response’s body. The PSR-7Response object provides several methods to inspect and manipulate its headers.

Get All Headers

You can fetch all HTTP response headers as an associative array with the PSR-7Response object’s getHeaders() method. The resultant associative array’s keysare the header names and its values are themselves a numeric array of stringvalues for their respective header name.

  1. $headers = $response->getHeaders();
  2. foreach ($headers as $name => $values) {
  3. echo $name . ": " . implode(", ", $values);
  4. }
Figure 5: Fetch and iterate all HTTP response headers as an associative array.

Get One Header

You can get a single header’s value(s) with the PSR-7 Response object’sgetHeader($name) method. This returns an array of values for the given headername. Remember, a single HTTP header may have more than one value!

  1. $headerValueArray = $response->getHeader('Vary');
Figure 6: Get values for a specific HTTP header.

You may also fetch a comma-separated string with all values for a given headerwith the PSR-7 Response object’s getHeaderLine($name) method. Unlike thegetHeader($name) method, this method returns a comma-separated string.

  1. $headerValueString = $response->getHeaderLine('Vary');
Figure 7: Get single header's values as comma-separated string.

Detect Header

You can test for the presence of a header with the PSR-7 Response object’shasHeader($name) method.

  1. if ($response->hasHeader('Vary')) {
  2. // Do something
  3. }
Figure 8: Detect presence of a specific HTTP header.

Set Header

You can set a header value with the PSR-7 Response object’swithHeader($name, $value) method.

  1. $newResponse = $oldResponse->withHeader('Content-type', 'application/json');
Figure 9: Set HTTP header

Reminder

The Response object is immutable. This method returns a copy of the Response object that has the new header value. This method is destructive, and it replaces existing header values already associated with the same header name.

Append Header

You can append a header value with the PSR-7 Response object’swithAddedHeader($name, $value) method.

  1. $newResponse = $oldResponse->withAddedHeader('Allow', 'PUT');
Figure 10: Append HTTP header

Reminder

Unlike the 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.

Remove Header

You can remove a header with the Response object’s withoutHeader($name) method.

  1. $newResponse = $oldResponse->withoutHeader('Allow');
Figure 11: Remove HTTP header

Reminder

The Response object is immutable. This method returns a copy of the Response object that has the appended header value.

The Response Body

An HTTP response typically has a body.

Just like the PSR-7 Request object, the PSR-7 Response object implementsthe body as an instance of Psr\Http\Message\StreamInterface. You can getthe HTTP response body StreamInterface instance with the PSR-7 Responseobject’s getBody() method. The getBody() method is preferable if theoutgoing HTTP response length is unknown or too large for available memory.

  1. $body = $response->getBody();
Figure 12: Get HTTP response body

The resultant Psr\Http\Message\StreamInterface instance provides the followingmethods 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 writecontent to the StreamInterface instance with its write() method like this:
  1. $body = $response->getBody();
  2. $body->write('Hello');
Figure 13: Write content to the HTTP response body

You can also replace the PSR-7 Response object’s body with an entirely newStreamInterface instance. This is particularly useful when you want to pipecontent from a remote destination (e.g. the filesystem or a remote API) intothe HTTP response. You can replace the PSR-7 Response object’s body withits withBody(StreamInterface $body) method. Its argument MUST be aninstance of Psr\Http\Message\StreamInterface.

  1. use GuzzleHttp\Psr7\LazyOpenStream;
  2. $newStream = new LazyOpenStream('/path/to/file', 'r');
  3. $newResponse = $oldResponse->withBody($newStream);
Figure 14: Replace the HTTP response body

Reminder

The Response object is immutable. This method returns a copy of the Response object that contains the new body.

Returning JSON

In it’s simplest form, JSON data can be returned with a default 200 HTTP status code.

  1. $data = array('name' => 'Bob', 'age' => 40);
  2. $payload = json_encode($data);
  3. $response->getBody()->write($payload);
  4. return $response
  5. ->withHeader('Content-Type', 'application/json');
Figure 15: Returning JSON with a 200 HTTP status code.

We can also return JSON data with a custom HTTP status code.

  1. $data = array('name' => 'Rob', 'age' => 40);
  2. $payload = json_encode($data);
  3. $response->getBody()->write($payload);
  4. return $response
  5. ->withHeader('Content-Type', 'application/json')
  6. ->withStatus(201);
Figure 16: Returning JSON with a 201 HTTP status code.

Reminder

The Response object is immutable. This method returns a copy of the Response object that has a new Content-Type header. This method is destructive, and it replaces the existing Content-Type header.

Returning a Redirect

You can redirect the HTTP client by using the Location header.

  1. return $response
  2. ->withHeader('Location', 'https://www.example.com')
  3. ->withStatus(302);
Figure 17: Returning a redirect to https://www.example.com