Home  >  Article  >  Backend Development  >  How to Output Custom HTTP Body Contents in CakePHP 3.4?

How to Output Custom HTTP Body Contents in CakePHP 3.4?

Susan Sarandon
Susan SarandonOriginal
2024-10-26 04:03:03849browse

How to Output Custom HTTP Body Contents in CakePHP 3.4?

Outputting Custom HTTP Body Contents with CakePHP 3.4

Unlike in previous versions, CakePHP 3.4 strictly enforces the separation of data manipulation and presentation in controllers. Echoing data directly can lead to unexpected errors.

To output custom HTTP body contents, CakePHP recommends using either the PSR-7 compliant response object or serialized views.

Configuring the Response Object

PSR-7 Compliant 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>

Deprecated Interface (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;<h3>Using Serialized Views</h3>
<pre class="brush:php;toolbar:false"><code class="php">$content = ['method' => __METHOD__, 'class' => get_called_class()];

$this->set('content', $content);
$this->set('_serialize', 'content');</code>

This requires you to enable the request handler component and configure the router to extend parsing for JSON requests (with .json appended to URLs) or use an appropriate request with an application/json accept header.

Conclusion

Echoing data directly in controllers is discouraged in CakePHP 3.4. Instead, use the response object or serialized views to reliably output custom HTTP body contents.

The above is the detailed content of How to Output Custom HTTP Body Contents in CakePHP 3.4?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn