我试图了解 PSR-7 是如何工作的,但我被卡住了!这是我的代码:
$app->get('/', function () {
$stream = new Stream('php://memory', 'rw');
$stream->write('Foo');
$response = (new Response())
->withHeader('Content-Type', 'text/html')
->withBody($stream);
});
我的 Response 对象正在构建,但现在我想发送它...
PSR-7 如何发送响应?我需要序列化吗?我可能错过了一件事......
请您参考如下方法:
就像完成一样,即使问题已经超过两年了:
响应是服务器向客户端发送的 HTTP 消息,是客户端向服务器发出请求的结果。
客户端需要一个字符串作为消息,由以下组成:
HTTP/<protocol-version> <status-code> <reason-phrase>
的形式); <header-name>: <comma-separ.-header-values>
”形式); 它看起来像这样(见 PSR-7 ):
HTTP/1.1 200 OK
Content-Type: text/html
vary: Accept-Encoding
This is the response body
为了发出响应,实际上必须执行三个操作:
棘手的部分由第三个操作表示。实现
ResponseInterface
的类的实例包含一个流对象作为消息体。并且这个对象必须转换成字符串并打印出来。这个任务很容易完成,因为流是一个实现
StreamInterface
的类的实例,它反过来强制定义了一个神奇的方法
__toString() 。
因此,通过执行前两个步骤并将输出函数(
echo
、
print_r
等)应用于响应实例的
getBody()
方法的结果,发射过程就完成了。
<?php
if (headers_sent()) {
throw new RuntimeException('Headers were already sent. The response could not be emitted!');
}
// Step 1: Send the "status line".
$statusLine = sprintf('HTTP/%s %s %s'
, $response->getProtocolVersion()
, $response->getStatusCode()
, $response->getReasonPhrase()
);
header($statusLine, TRUE); /* The header replaces a previous similar header. */
// Step 2: Send the response headers from the headers list.
foreach ($response->getHeaders() as $name => $values) {
$responseHeader = sprintf('%s: %s'
, $name
, $response->getHeaderLine($name)
);
header($responseHeader, FALSE); /* The header doesn't replace a previous similar header. */
}
// Step 3: Output the message body.
echo $response->getBody();
exit();
P.S:对于大量数据,最好使用
php://temp
流而不是
php://memory
。
Here 是原因。