Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

233
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda