與先前的版本不同,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中文網其他相關文章!