我试图了解PSR-7是如何工作的,但我被卡住了!下面是我的代码:
$app->get('/', function () {
$stream = new Stream('php://memory', 'rw');
$stream->write('Foo');
$response = (new Response())
->withHeader('Content-Type', 'text/html')
->withBody($stream);
});我的响应对象是build,但现在我想发送它...PSR-7如何发送响应?我需要序列化吗?我可能漏掉了一件事。
发布于 2018-02-10 13:03:27
就像完成一样,即使这个问题已经超过两年了:
响应是服务器发送给客户端的HTTP消息,这是客户端向服务器发出请求的结果。
客户端期望一个字符串作为消息,由以下部分组成:
它看起来像这样(参见PSR-7):
HTTP/1.1 200 OK
Content-Type: text/html
vary: Accept-Encoding
This is the response body为了发出响应,必须实际执行三个操作:
将“状态行”发送到客户端(使用
棘手的部分由第三个操作表示。实现ResponseInterface的类的实例包含一个流对象作为消息体。并且此对象必须转换为字符串并打印出来。这项任务很容易完成,因为流是实现StreamInterface的类的实例,而后者又强制执行神奇方法的定义。
因此,通过执行前两个步骤并对响应实例的getBody()方法的结果应用输出函数(echo、print_r等),发送过程就完成了。
<?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();附言:对于大量数据,最好使用php://temp流,而不是php://memory。Here是原因所在。
发布于 2015-10-23 23:17:12
Psr-7只是对http消息进行建模。它没有发送响应的功能。您需要使用另一个使用PSR-7消息的库。你可以看看zend stratigility或者类似的东西
https://stackoverflow.com/questions/33304790
复制相似问题