CakePHP3.4: How to send a json object response?

萝らか妹 提交于 2019-12-02 03:48:40

Check the migration guide, the new reponse methods follow the PSR-7 immutability pattern.

Request & Response Deprecations

The bulk of deprecations for 3.4 are in the Request and Response objects. The existing methods that modify objects in-place are now deprecated, and superseded by methods that follow the immutable object patterns described in the PSR-7 standard.

Cookbook > 3.x Migration Guide > 3.4 Migration Guide > Request & Response Deprecations

Adopting Immutable Responses

Before you migrate your code to use the new response methods you should be aware of the conceptual differences the new methods have. The immutable methods are generally indicated using a with prefix. For example, withLocation(). Because these methods operate in an immutable context, they return new instances which you need to assign to variables or properties. If you had controller code that looked like:

$response = $this->response;
$response->location('/login')
$response->header('X-something', 'a value');

If you were to simply find & replace method names your code would break. Instead you must now use code that looks like:

$this->response = $this->response
    ->withLocation('/login')
    ->withHeader('X-something', 'a value');

There are a few key differences:

The result of your changes is re-assigned to $this->response. This is critical to preserving the intent of the above code. The setter methods can all be chained together. This allows you to skip storing all the intermediate objects.

Cookbook > 3.x Migration Guide > 3.4 Migration Guide > Adopting Immutable Responses

Long story short, in your case you must return the new request object created by the immutable methods:

return $this->response
    ->withType('application/json');
    ->withStringBody($jsonSites);

If you wouldn't return a response object, then you'd need to reassign the new reponse to $this->response as mentioned in the above quote.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!