PSR-7 and Value Objects

Slim supports PSR-7 interfaces forits Request and Response objects. This makes Slim flexible because it canuse any PSR-7 implementation. For example, you could return an instance of GuzzleHttp\Psr7\CachingStream or any instancereturned by the GuzzleHttp\Psr7\stream_for() function.

Slim provides its own PSR-7 implementation so that it works out of the box. However,you are free to replace Slim’s default PSR-7 objects with a third-party implementation.Just override the application container’s request and response services sothey return an instance of Psr\Http\Message\ServerRequestInterface andPsr\Http\Message\ResponseInterface, respectively.

Value objects

Request and Response objects are immutable value objects.They can be “changed” only by requesting a cloned version that has updatedproperty values. Value objects have a nominal overhead because they must becloned when their properties are updated. This overhead does not affectperformance in any meaningful way.

You can request a copy of a value object by invoking any of its PSR-7interface methods (these methods typically have a with prefix). For example,a PSR-7 Response object has a withHeader($name, $value) method that returns acloned value object with the new HTTP header.

  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('/foo', function (Request $request, Response $response, array $args) {
  8. $payload = json_encode(['hello' => 'world'], JSON_PRETTY_PRINT);
  9. $response->getBody()->write($payload);
  10. return $response->withHeader('Content-Type', 'application/json');
  11. });
  12. $app->run();

The PSR-7 interface provides these methods to transform Request and Responseobjects:

  • withProtocolVersion($version)
  • withHeader($name, $value)
  • withAddedHeader($name, $value)
  • withoutHeader($name)
  • withBody(StreamInterface $body)The PSR-7 interface provides these methods to transform Request objects:

  • withMethod($method)

  • withUri(UriInterface $uri, $preserveHost = false)
  • withCookieParams(array $cookies)
  • withQueryParams(array $query)
  • withUploadedFiles(array $uploadedFiles)
  • withParsedBody($data)
  • withAttribute($name, $value)
  • withoutAttribute($name)The PSR-7 interface provides these methods to transform Response objects:

  • withStatus($code, $reasonPhrase = '')Refer to the PSR-7 documentation for more information about these methods.