与以前的版本不同,CakePHP 3.4 严格强制控制器中数据操作和表示的分离。直接回显数据可能会导致意外错误。
要输出自定义 HTTP 正文内容,CakePHP 建议使用符合 PSR-7 的响应对象或序列化视图。
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
<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>
这需要您启用请求处理程序组件并配置路由器以扩展对 JSON 请求的解析(将 .json 附加到 URL)或使用带有 application/json 接受的适当请求header.
CakePHP 3.4 中不鼓励直接在控制器中回显数据。相反,使用响应对象或序列化视图来可靠地输出自定义 HTTP 正文内容。
以上是如何在 CakePHP 3.4 中输出自定义 HTTP Body 内容?的详细内容。更多信息请关注PHP中文网其他相关文章!