Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

235
Visualizações
Using GuzzleHttp/Psr7/Response Correctly

Not sure what is the correct way to display in a php page a Psr7 Guzzle Response.

Right now, I am doing:

use GuzzleHttp\Psr7\BufferStream;
use GuzzleHttp\Psr7\Response;

class Main extends \pla\igg\Main
{
    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();

    }
}

Is there a more OOP way to display the response?

about 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

A more OOP way of doing the same thing is to create a Sender object that requires a ResponseInterface in its constructor. This class would be responsible for setting headers, clearing buffers and render the response:

use Psr\Http\Message\ResponseInterface;

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();
        }
    }
}

Use it like this:

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

Better yet, you could inject the Sender into your app object and transform it in a class variable, so you'd call it like this:

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

I'll leave it as a reader's exercise to implement getters and setters for the Response object, plus a method to receive some content string and transform it into a Response object internally.

about 4 years ago · Santiago Trujillo Relatório

0

Guzzle is a library for doing HTTP calls inside your app, it has nothing to do with the end user communication.

If you need to send specific headers to your end user, just use http_response_code() (that you are already using), header() and echo. Or see the docs for your framework, if you use one (Symfony, Slim, whatever).

about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda