我的应用程序中的大部分响应都是 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/