Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

234
Views
Usando GuzzleHttp/Psr7/Response correctamente

No estoy seguro de cuál es la forma correcta de mostrar en una página php una respuesta Psr7 Guzzle.

Ahora mismo, estoy haciendo:

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

¿Hay una forma más OOP de mostrar la respuesta?

about 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Una forma más OOP de hacer lo mismo es crear un objeto Sender que requiera una ResponseInterface en su constructor. Esta clase sería responsable de establecer encabezados, borrar búferes y generar la respuesta:

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

Úsalo así:

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

Mejor aún, podría inyectar el remitente en el objeto de su aplicación y transformarlo en una variable de clase, por lo que lo llamaría así:

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

Lo dejaré como un ejercicio de lectura para implementar getters y setters para el objeto Response, además de un método para recibir una cadena de contenido y transformarla en un objeto Response internamente.

about 4 years ago · Santiago Trujillo Report

0

Guzzle es una biblioteca para realizar llamadas HTTP dentro de su aplicación, no tiene nada que ver con la comunicación del usuario final.

Si necesita enviar encabezados específicos a su usuario final, simplemente use http_response_code() (que ya está usando), header() y echo . O vea los documentos para su marco, si usa uno ( Symfony , Slim , lo que sea).

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!