【问题标题】:Accessing the Data of a Slim 3 Response Object访问 Slim 3 响应对象的数据
【发布时间】:2020-09-05 17:15:50
【问题描述】:

我正在使用一个名为 Slim 3 的 PHP 框架,我想检查我的 Response 对象,我想知道为什么这是不可能的。

官方文档指出 Response` 对象实现了 PSR 7 ResponseInterface,它允许我检查主体。

当我var_dump($response->getBody(); 时,我只看到protected 正文,而我在任何地方都找不到我的$stack 内容。

文档说明了这一点,我认为这就是原因。你能确认一下吗?

提醒 Response 对象是不可变的。此方法返回包含新主体的 Response 对象的副本。

来源:https://www.slimframework.com/docs/objects/response.html

PHP 控制器类

class Controller
{
    public function index($request, $response, $args)
    {
        // code

        $stack    = array($cars, $manufacturers);
        $response = $response->withJson($stack);

        return $response->withStatus(200);
    }
}

var_dump 的输出

class Slim\Http\Response#201 (5) {
  protected $status =>
  int(200)
  protected $reasonPhrase =>
  string(2) "OK"
  protected $protocolVersion =>
  string(3) "1.1"
  protected $headers =>
  class Slim\Http\Headers#200 (1) {
    protected $data =>
    array(1) {
      'content-type' =>
      array(2) {
        ...
      }
    }
  }
  protected $body =>
  class Slim\Http\Body#202 (7) {
    protected $stream =>
    resource(87) of type (stream)
    protected $meta =>
    array(6) {
      'wrapper_type' =>
      string(3) "PHP"
      'stream_type' =>
      string(4) "TEMP"
      'mode' =>
      string(3) "w+b"
      'unread_bytes' =>
      int(0)
      'seekable' =>
      bool(true)
      'uri' =>
      string(10) "php://temp"
    }
    protected $readable =>
    NULL
    protected $writable =>
    bool(true)
    protected $seekable =>
    NULL
    protected $size =>
    NULL
    protected $isPipe =>
    NULL
  }
}

【问题讨论】:

    标签: php slim slim-3


    【解决方案1】:

    内容被写入 HTTP 响应正文流。

    $content = $response->getBody()->__toString();
    

    $content = (string)$response->getBody();
    

    【讨论】:

    • 请问这是您通常掌握的特殊 PHP 知识,还是您必须查找这些知识才能为我提供此答案?我觉得这很惊人。
    • PSR-11 的文档包含此信息。我还必须搜索并尝试一些东西,直到成功为止。
    猜你喜欢
    • 1970-01-01
    • 2016-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-20
    相关资源
    最近更新 更多