IT序号网

php之使用 PSR-7 发出响应

pander-it 2025年02月15日 编程语言 17 0

我试图了解 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 的列表(每个都采用“<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 
    

    为了发出响应,实际上必须执行三个操作:
  • 将“状态行”发送给 到客户端(使用 header() PHP 函数)。
  • 将 header 列表发送给 到客户端 (dito)。
  • 输出 消息正文。

  • 棘手的部分由第三个操作表示。实现 ResponseInterface 的类的实例包含一个流对象作为消息体。并且这个对象必须转换成字符串并打印出来。这个任务很容易完成,因为流是一个实现 StreamInterface 的类的实例,它反过来强制定义了一个神奇的方法 __toString()

    因此,通过执行前两个步骤并将输出函数( echoprint_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://memoryHere 是原因。


    评论关闭
    IT序号网

    微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!