如何使用PSR-7响应



我的应用程序中的大多数响应要么是视图,要么是JSON。我不知道如何将它们放在PSR-7中实现ResponseInterface的对象中。

以下是我目前所做的:

// 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 HttpResponse(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创建的文件资源时,它会起作用,但我如何使用字符串呢?

更新

我的代码中的HttpResponse实际上是我自己在PSR-7中实现的ResponseInterface。我已经实现了所有的接口,因为我目前一直使用PHP 5.3,我找不到任何与PHP<5.4.这是HttpResponse:的构造函数

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;
}

定义私有成员$content如下:

private $content = '';

还有一个吸气剂:

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

你可以走了!

最新更新