首頁  >  文章  >  後端開發  >  如何在 CakePHP 3.4 中輸出自訂 HTTP Body 內容?

如何在 CakePHP 3.4 中輸出自訂 HTTP Body 內容?

Susan Sarandon
Susan Sarandon原創
2024-10-26 04:03:03849瀏覽

How to Output Custom HTTP Body Contents in CakePHP 3.4?

使用 CakePHP 3.4 輸出自訂 HTTP 正文內容

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

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn