首页  >  文章  >  后端开发  >  如何使用 CakePHP 3.4 和 PSR-7 输出自定义 HTTP 响应正文内容?

如何使用 CakePHP 3.4 和 PSR-7 输出自定义 HTTP 响应正文内容?

Patricia Arquette
Patricia Arquette原创
2024-10-27 12:22:02360浏览

How to Output Custom HTTP Response Body Contents Using CakePHP 3.4 and PSR-7?

使用 CakePHP 3.4 和 PSR-7 自定义 HTTP 响应正文输出

CakePHP 3.4 引入了使用符合 PSR-7 的响应对象。 直接通过 echo 回显数据 现在会由于严格的标头检查而触发错误。

控制器不应回显数据。 相反,请使用以下方法输出自定义 HTTP 正文内容:

使用 PSR-7 响应接口:

<code class="php">$content = json_encode(['method' => __METHOD__, 'class' => get_called_class()]);

$this->response = $this->response->withStringBody($content);
$this->response = $this->response->withType('json');

return $this->response;</code>

使用已弃用的响应接口(CakePHP 3.4.3 之前):

<code class="php">$content = json_encode(['method' => __METHOD__, 'class' => get_called_class()]);

$this->response->body($content);
$this->response->type('json');

return $this->response;</code>

使用序列化视图:

<code class="php">$content = ['method' => __METHOD__, 'class' => get_called_class()];

$this->set('content', $content);
$this->set('_serialize', 'content');</code>

此方法需要请求处理程序组件和正确的 URL 或请求标头来触发 JSON 视图渲染。

参考文献:

  • [食谱:控制器和操作](https://book.cakephp.org/4/en/controllers.html#controller-actions)
  • [食谱:请求和响应对象以及设置正文](https://book.cakephp.org/4/en/controllers.html#setting-the-body)
  • [食谱:视图和 JSON/XML](https://book.cakephp.org/4/en/views.html#json-and-xml-views)
  • [PHP 图:PSR-7 HTTP 消息接口] (https://www.php-fig.org/psr/psr-7/)

以上是如何使用 CakePHP 3.4 和 PSR-7 输出自定义 HTTP 响应正文内容?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn