PSR-7 和值对象
Slim 支持 PSR-7 接口用于其请求和响应对象。这使得 Slim 具有灵活性,因为它可以使用 任何 PSR-7 实现。例如,您可以返回 GuzzleHttp\Psr7\CachingStream 的实例或由 GuzzleHttp\Psr7\stream_for() 函数返回的任何实例。
Slim 提供了自己的 PSR-7 实现。但是,您可以自由地 安装第三方实现。
值对象
请求和响应对象是 不可变值对象。它们只能通过请求克隆版本来更改其属性值。值对象在更新其属性时需要进行克隆操作,因此会产生一定开销。然而,这种开销对性能没有实质性影响。
您可以通过调用其 PSR-7 接口方法(这些方法通常以 with 为前缀)来请求一个值对象的副本。例如,PSR-7 响应对象具有 withHeader($name, $value) 方法,该方法返回一个包含新 HTTP 头的克隆值对象。
<?php
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\Factory\AppFactory;
require __DIR__ . '/../vendor/autoload.php';
$app = AppFactory::create();
$app->get('/foo', function (Request $request, Response $response, array $args) {
$payload = json_encode(['hello' => 'world'], JSON_PRETTY_PRINT);
$response->getBody()->write($payload);
return $response->withHeader('Content-Type', 'application/json');
});
$app->run();
PSR-7 接口提供了以下方法用于转换请求和响应对象:
withProtocolVersion($version)withHeader($name, $value)withAddedHeader($name, $value)withoutHeader($name)withBody(StreamInterface $body)
PSR-7 接口提供了以下方法用于转换请求对象:
withMethod($method)withUri(UriInterface $uri, $preserveHost = false)withCookieParams(array $cookies)withQueryParams(array $query)withUploadedFiles(array $uploadedFiles)withParsedBody($data)withAttribute($name, $value)withoutAttribute($name)
PSR-7 接口提供了以下方法用于转换响应对象:
withStatus($code, $reasonPhrase = '')
有关这些方法的更多信息,请参阅 PSR-7 文档。