Slim 支援 PSR-7 的 Request 和 Response 物件的介面。這讓 Slim 具有彈性,因為它可以使用任何 PSR-7 實作。例如,您可以回傳 GuzzleHttp\Psr7\CachingStream
或由 GuzzleHttp\Psr7\stream_for()
函數回傳的任何實例。
Slim 提供了自己的 PSR-7 實作。不過,您可以自由安裝第三方實作。
Request 和 Response 物件是 不可變值物件。它們只能透過要求更新屬性值的 клонов來「變更」。由於在更新其屬性時必須複製值物件,因此它們會產生 номина費用。此費用不會對效能造成任何有意義的影響。
您可以透過呼叫其任何 PSR-7 介面方法(這些方法通常有 with
前綴)來要求複製一個值物件。例如,PSR-7 Response 物件有一個 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 介面提供這些方法轉換 Request 和 Response 物件
withProtocolVersion($version)
withHeader($name, $value)
withAddedHeader($name, $value)
withoutHeader($name)
withBody(StreamInterface $body)
PSR-7 介面提供這些方法轉換 Request 物件
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 介面提供這些方法轉換 Response 物件
withStatus($code, $reasonPhrase = '')
請參閱 PSR-7 文件 以取得關於這些方法的更多資訊。