Home >Backend Development >PHP Tutorial >How to Output Custom HTTP Response Body Contents Using CakePHP 3.4 and PSR-7?
Custom HTTP Response Body Output with CakePHP 3.4 and PSR-7
CakePHP 3.4 introduces the use of PSR-7 compliant response objects. Echoing data directly via echo can now trigger errors due to strict header checks.
Controllers should not echo data. Instead, use the following methods to output custom HTTP body contents:
Using PSR-7 Response Interface:
<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>
Using Deprecated Response Interface (prior to CakePHP 3.4.3):
<code class="php">$content = json_encode(['method' => __METHOD__, 'class' => get_called_class()]); $this->response->body($content); $this->response->type('json'); return $this->response;</code>
Using Serialized Views:
<code class="php">$content = ['method' => __METHOD__, 'class' => get_called_class()]; $this->set('content', $content); $this->set('_serialize', 'content');</code>
This approach requires the Request Handler Component and proper URL or request headers to trigger JSON view rendering.
References:
The above is the detailed content of How to Output Custom HTTP Response Body Contents Using CakePHP 3.4 and PSR-7?. For more information, please follow other related articles on the PHP Chinese website!