php - 如何使用 PSR-7 响应?

标签 php stream httpresponse php-stream-wrappers psr-7

我的应用程序中的大部分响应都是 View 或 JSON。我不知道如何将它们放入实现 ResponseInterface 的对象中在 PSR-7 .

这是我目前所做的:

// Views
header('Content-Type: text/html; charset=utf-8');
header('Content-Language: en-CA');
echo $twig->render('foo.html.twig', array(
    'param' => 'value'
    /* ... */
));

// JSON
header('Content-Type: application/json; charset=utf-8');
echo json_encode($foo);

这是我尝试用 PSR-7 做的事情:

// Views
$response = new Http\Response(200, array(
    'Content-Type' => 'text/html; charset=utf-8',
    'Content-Language' => 'en-CA'
));

// what to do here to put the Twig output in the response??

foreach ($response->getHeaders() as $k => $values) {
    foreach ($values as $v) {
        header(sprintf('%s: %s', $k, $v), false);
    }
}
echo (string) $response->getBody();

而且我认为对于具有不同 header 的 JSON 响应来说应该是相似的。据我了解,邮件正文是 StreamInterface当我尝试输出使用 fopen 创建的文件资源时它会起作用,但我如何使用字符串来输出?

更新

Http\Response 在我的代码中实际上是我自己对 PSR-7 中的 ResponseInterface 的实现。我已经实现了所有接口(interface),因为我目前坚持使用 PHP 5.3,但我找不到任何与 PHP < 5.4 兼容的实现。下面是 Http\Response 的构造函数:

public function __construct($code = 200, array $headers = array()) {
    if (!in_array($code, static::$validCodes, true)) {
        throw new \InvalidArgumentException('Invalid HTTP status code');
    }

    parent::__construct($headers);
    $this->code = $code;
}

我可以修改我的实现以接受输出作为构造函数参数,或者我可以使用 MessageInterface 实现的 withBody 方法。不管我怎么做,问题都是如何将字符串放入流中

最佳答案

ResponseInterface 扩展了 MessageInterface,它提供了您找到的 getBody() getter。 PSR-7 期望实现 ResponseInterface 的对象是不可变的,如果不修改构造函数,您将无法实现这一点。

由于您运行的是 PHP < 5.4(并且无法有效地进行类型提示),请按如下方式修改它:

public function __construct($code = 200, array $headers = array(), $content='') {
  if (!in_array($code, static::$validCodes, true)) {
    throw new \InvalidArgumentException('Invalid HTTP status code');
  }

  parent::__construct($headers);
  $this->code = $code;
  $this->content = (string) $content;
}

定义一个私有(private)成员$content如下:

private $content = '';

还有一个 setter/getter :

public function getBody() {
  return $this->content;
}

一切顺利!

关于php - 如何使用 PSR-7 响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33853893/

相关文章:

php - 如何修复 PHP MySQL 中达到 508 资源限制

c++ - 只要应用程序运行就一直打开错误日志是否可以接受?

Node.JS 数据输入流

javascript - NetSuite - 将文件写入 Suitelet 响应以直接下载文件

django - 如何使用 Django HttpResponseRedirect 提供规范 URL?

javascript - 我可以创建一个同时适用于 HTTP 和 HTTPS 的 javascript 文件吗

php - 在 PHP 中提取 XML 文本时保留 <br>

javascript - 使用 php 动态添加表单字段

flutter - 实现BlocProvider抖动的差异

javascript - Django/Javascript 交互中 POST 无响应