rin*_*t.6 5 php stream httpresponse php-stream-wrappers psr-7
我的应用程序中的大多数响应要么是视图,要么是 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);
Run Code Online (Sandbox Code Playgroud)
这是我试图用 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();
Run Code Online (Sandbox Code Playgroud)
而且我想对于具有不同标头的 JSON 响应来说,它会是相似的。据我了解,消息正文是 aStreamInterface并且当我尝试输出使用fopen它创建的文件资源时它可以工作,但是我如何使用字符串来执行此操作?
更新
Http\Response在我的代码中实际上是我自己ResponseInterface在 PSR-7 中的实现。我已经实现了所有接口,因为我目前坚持使用 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;
}
Run Code Online (Sandbox Code Playgroud)
我可以修改我的实现以接受输出作为构造函数参数,或者我可以使用实现的withBody方法MessageInterface。不管我怎么做,问题是如何将字符串放入流中。
ResponseInterfaceextends 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;
}
Run Code Online (Sandbox Code Playgroud)
定义私有成员$content如下:
private $content = '';
Run Code Online (Sandbox Code Playgroud)
还有一个吸气剂:
public function getBody() {
return $this->content;
}
Run Code Online (Sandbox Code Playgroud)
你就可以出发了!