Home >Backend Development >PHP Tutorial >How to Output Custom HTTP Response Body Contents Using CakePHP 3.4 and PSR-7?

How to Output Custom HTTP Response Body Contents Using CakePHP 3.4 and PSR-7?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-27 12:22:02441browse

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:

  • [Cookbook: Controllers & Actions](https://book.cakephp.org/4/en/controllers.html#controller-actions)
  • [Cookbook: Request & Response Objects & Setting Body](https://book.cakephp.org/4/en/controllers.html#setting-the-body)
  • [Cookbook: Views & JSON/XML](https://book.cakephp.org/4/en/views.html#json-and-xml-views)
  • [PHP FIG: PSR-7 HTTP Message Interfaces](https://www.php-fig.org/psr/psr-7/)

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!

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