正确使用GuzzleHttp/Psr7/Response

原学程将引见准确应用GuzzleHttp/Psr七/Response的处置办法,这篇学程是从其余处所瞅到的,而后减了1些海外法式员的疑问与解问,愿望能对于您有所赞助,佳了,上面开端进修吧。

正确使用GuzzleHttp/Psr7/Response 教程 第1张

成绩描写

没有肯定在php页里中显示Psr七痛饮呼应的准确方法。

如今,我正在做:

use GuzzleHttpPsr七BufferStream;
use GuzzleHttpPsr七Response;

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('二0一');
  $response = $response->withHeader("Content-type", "text/plain");
  $response = $response->withAddedHeader("IGG", "0.四.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

做异样工作的1种更里向对于象的办法是创立1个推举谜底对于象,该对于象在其结构函数中须要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和吸收某些实质字符串并在外部将其转换为呼应对于象的办法留给读者演习。

佳了闭于准确应用GuzzleHttp/Psr七/Response的学程便到这里便停止了,愿望趣模板源码网找到的这篇技巧文章能赞助到年夜野,更多技巧学程不妨在站内搜刮。