首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用PSR-7发出响应

使用PSR-7发出响应
EN

Stack Overflow用户
提问于 2015-10-23 22:25:54
回答 2查看 2.9K关注 0票数 4

我试图了解PSR-7是如何工作的,但我被卡住了!下面是我的代码:

代码语言:javascript
复制
$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如何发送响应?我需要序列化吗?我可能漏掉了一件事。

EN

回答 2

Stack Overflow用户

发布于 2018-02-10 13:03:27

就像完成一样,即使这个问题已经超过两年了:

响应是服务器发送给客户端的HTTP消息,这是客户端向服务器发出请求的结果。

客户端期望一个字符串作为消息,由以下部分组成:

  • a "status line“(格式为list of headers (每个标题的格式均为空行;
  • a message body<>E215(一个字符串)。

它看起来像这样(参见PSR-7):

代码语言:javascript
复制
HTTP/1.1 200 OK
Content-Type: text/html
vary: Accept-Encoding

This is the response body

为了发出响应,必须实际执行三个操作:

将“状态行”发送到客户端(使用

  1. Send PHP function).
  2. Send (dito).
  3. Output 消息体的头列表。

棘手的部分由第三个操作表示。实现ResponseInterface的类的实例包含一个流对象作为消息体。并且此对象必须转换为字符串并打印出来。这项任务很容易完成,因为流是实现StreamInterface的类的实例,而后者又强制执行神奇方法的定义。

因此,通过执行前两个步骤并对响应实例的getBody()方法的结果应用输出函数(echoprint_r等),发送过程就完成了。

代码语言:javascript
复制
<?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://memoryHere是原因所在。

票数 7
EN

Stack Overflow用户

发布于 2015-10-23 23:17:12

Psr-7只是对http消息进行建模。它没有发送响应的功能。您需要使用另一个使用PSR-7消息的库。你可以看看zend stratigility或者类似的东西

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33304790

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档