【问题标题】:How to use PSR-7 responses?如何使用 PSR-7 响应?
【发布时间】:2016-02-24 13:07:42
【问题描述】:

我的应用程序中的大多数响应是视图或 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 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。我已经实现了所有接口,因为我目前坚持使用 PHP 5.3,并且找不到与 PHP 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 方法。不管我怎么做,问题是如何将字符串放入流中

【问题讨论】:

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


    【解决方案1】:

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

    当你运行 PHP

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

    你很高兴!

    【讨论】:

    • 我没有使用 Slim,Http\Response 实际上是我自己实现的ResponseInterface(构造函数有两个参数)。我已经在MessageInterface 中实现了withBody 方法,但是它采用StreamInterface 作为参数,所以同样的问题仍然存在于创建字符串流。我可以修改ResponseInterface 的实现以接受字符串$body,但我不知道如何实现它...
    • @rink.attendant.6:那么,显然,您需要为 body 或构造函数参数实现 setter。因为,根据 PSR-7,所有响应对象都应该是不可变的,它必须是构造函数参数。您可以发布Response 对象的代码吗?之后我会编辑我的答案。
    • 我已经用Response 对象的构造函数更新了这个问题。除了检查代码是否有效的方法外,接口中实现三个方法的最低限度。
    • 这行得通……但我不应该用getBody()返回StreamInterface吗?至少我希望一个覆盖方法的子类返回与该接口兼容的对象
    • @rink.attendant.6:如果您想走那么远,请获取StreamInterface 接口。这不适合评论,所以我会再次编辑。但是,对于大多数用例,目前主要框架仅真正使用__toString()
    猜你喜欢
    • 2017-09-13
    • 1970-01-01
    • 2019-03-27
    • 1970-01-01
    • 2019-12-11
    • 2018-07-25
    • 1970-01-01
    • 2015-11-11
    • 1970-01-01
    相关资源
    最近更新 更多