正确使用GuzzleHttp/Psr7/Response

2022-09-02 00:00:00 php guzzle psr-7

不确定在php页面中显示Psr7狂饮响应的正确方式。

现在,我正在做:

use GuzzleHttpPsr7BufferStream;
use GuzzleHttpPsr7Response;

class Main extends plaiggMain
{
    function __construct()
    {

        $stream = new BufferStream();
        $stream->write("Hello I am a buffer");

        $response = new Response();
        $response = $response->withBody($stream);
        $response = $response->withStatus('201');
        $response = $response->withHeader("Content-type", "text/plain");
        $response = $response->withAddedHeader("IGG", "0.4.0");

        //Outputing the response
        http_response_code($response->getStatusCode());

        foreach ($response->getHeaders() as $strName => $arrValue)
        {
            foreach ($arrValue as $strValue)
            {
                header("{$strName}:{$strValue}");
            }
        }


        echo $response->getBody()->getContents();

    }
}

是否有更面向对象的方式来显示响应?

Sender

做同样事情的一种更面向对象的方法是创建一个推荐答案对象,该对象在其构造函数中需要ResponseInterface。此类将负责设置标头、清除缓冲区并呈现响应:

use PsrHttpMessageResponseInterface;

class Sender
{
    protected $response;

    public function __construct(ResponseInterface $response)
    {
        $this->response = $response;
    }

    public function send(): void
    {
        $this->sendHeaders();
        $this->sendContent();
        $this->clearBuffers();
    }

    protected function sendHeaders(): void
    {
        $response = $this->response;
        $headers  = $response->getHeaders();
        $version  = $response->getProtocolVersion();
        $status   = $response->getStatusCode();
        $reason   = $response->getReasonPhrase();

        $httpString = sprintf('HTTP/%s %s %s', $version, $status, $reason);

        // custom headers
        foreach ($headers as $key => $values) {
            foreach ($values as $value) {
                header($key.': '.$value, false);
            }
        }

        // status
        header($httpString, true, $status);
    }

    protected function sendContent()
    {
        echo (string) $this->response->getBody();
    }

    protected function clearBuffers()
    {
        if (function_exists('fastcgi_finish_request')) {
            fastcgi_finish_request();
        } elseif (PHP_SAPI !== 'cli') {
            $this->closeOutputBuffers();
        }
    }

    private function closeOutputBuffers()
    {
        if (ob_get_level()) {
            ob_end_flush();
        }
    }
}

这样使用:

$sender = new Sender($response);
$sender->send();

更好的是,您可以将Sender注入到您的应用程序对象中,并将其转换为类变量,因此您可以这样调用它:

function renderAllMyCoolStuff()
{
    $this->sender->send();
}

我将把实现响应对象的getter和setter以及接收某些内容字符串并在内部将其转换为响应对象的方法留给读者练习。

相关文章