首頁  >  文章  >  後端開發  >  如何使用 CakePHP 3.4 輸出自訂 HTTP 正文?

如何使用 CakePHP 3.4 輸出自訂 HTTP 正文?

DDD
DDD原創
2024-10-26 17:42:30732瀏覽

How to Output Custom HTTP Body with CakePHP 3.4?

使用 CakePHP 3.4 輸出自訂 HTTP 正文

CakePHP 3.4 引入了更嚴格的標頭處理方法,禁止在控制器內直接回顯資料。嘗試回顯內容(如下圖)會導致錯誤「無法發出標頭」:

<code class="php">public function test() {
    $this->autoRender = false;
    echo json_encode(['method' => __METHOD__, 'class' => get_called_class()]);
}</code>

為什麼CakePHP 抱怨

CakePHP 中不鼓勵這種做法基於多種原因:

  • 它可能會導致測試環境中無法辨識資料。
  • 它會幹擾設定正確標頭的能力。
  • 它可能會導致截斷data.

正確的輸出方法

發送自訂輸出有兩種建議方法:

  1. 設定回應物件:

    使用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>
  2. 使用序列化視圖:

    <code class="php">$content = ['method' => __METHOD__, 'class' => get_called_class()];
    
    $this->set('content', $content);
    $this->set('_serialize', 'content');</code>

    此方法需要請求處理程序組件和適當的URL 映射才能利用JSON 。

參考資料

有關更多信息,請參閱以下資源:

  • Cookbook:控制器>控制器操作
  • 食譜:請求與回應物件>設定身體
  • 食譜:檢視> JSON 和XML 檢視
  • PHP Fig 標準:PSR-7 HTTP 訊息介面

以上是如何使用 CakePHP 3.4 輸出自訂 HTTP 正文?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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