首頁  >  文章  >  後端開發  >  如何使用 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>

使用已棄用>

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

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

return $this->response;</code>

使用已棄棄>使用已棄用>使用的回應介面(CakePHP 3.4.3 之前):

<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