How to Output Custom HTTP Body Contents in CakePHP 3.4?

Susan Sarandon
Release: 2024-10-26 04:03:03
Original
848 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!