我的应用程序中的大多数响应要么是视图,要么是JSON。我不知道如何将它们放在在PSR-7中实现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();我认为JSON响应与不同的标题类似。据我所知,消息体是一个StreamInterface,当我试图输出用fopen创建的文件资源时,它可以工作,但是如何使用字符串呢?
更新
代码中的Http\Response实际上是我自己在PSR-7中实现的ResponseInterface。我已经实现了所有的接口,因为我目前使用的是PHP5.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实现的MessageInterface方法。不管我是怎么做的,问题是如何将字符串导入流。
发布于 2015-11-22 11:21:03
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;
}按照以下方式定义私有成员$content:
private $content = '';和一个得奖者:
public function getBody() {
return $this->content;
}你就可以走了!
https://stackoverflow.com/questions/33853893
复制相似问题