CakePHP3.4:如何发送json对象响应?
我尝试迁移到3.4,并有问题发送json对象。 高达3.3,我用下面的代码:CakePHP3.4:如何发送json对象响应?
$jsonSites = json_encode([
'reqLocation' => [
'latitude' => $latitude,
'longitude' => $longitude
],
'sites' => $sitesList,
'discoveryBooks' => $discoveryBooksList,
'deleteSites' => !empty($inDeviceSites) ? [$inDeviceSites] : [],
'deleteBooks' => !empty($inDeviceBooks) ? [$inDeviceBooks] : []
]);
$this->response->type('application/json');
$this->response->body($jsonSites);
而且我的客户收到此类对象:
{
"reqLocation": {
"latitude": 48.080563,
"longitude": 4.4649
},
"sites": [
{
"id": 5076,
"name": "...",
"modified": "2017-01-28T03:03:23+00:00",
"directory_name": "fr/26/26120_56cc30ea4d907",
"type": "portail",
"longitude": 7.031953,
"latitude": 47.939468,
"image_0": "jpg",
"picto_color": "#FFDDDDDD",
"agthemes": [],
"distance": 131.29188575851,
"category": 1281,
"category_name": "Jardin",
"sitecategories": [
{
"id": 10,
"code": 1281,
"name_fr": "Jardin",
"_joinData": {
"id": 1876,
"site_id": 5076,
"site_category_id": 10,
"authorized": true
}
},
{
"id": 33,
"code": 1283,
"name_fr": "Jardin botanique",
"_joinData": {
"id": 5693,
"site_id": 5076,
"site_category_id": 33,
"authorized": true
}
}
]
},
],
"discoveryBooks": [],
"deleteSites": [],
"deleteBooks": []
}
所以,现在我刚刚更换过时的应对方法,如认为:
编辑:当然,我返回响应对象,但不能像在这里完成!
$this->response->withType('application/json');
$this->response->withStringBody($jsonSites);
return $this->response;
但现在我的客户端没有收到任何东西。我也试过邮差,没事!
怎么了?
查看迁移指南,新的响应方法遵循PSR-7不变性模式。
请求&响应弃用
弃用的为3.4散装处于
Request
和Response
对象。现有的修改对象的现有方法现在不支持 ,并且被在PSR-7标准中描述的不可变对象 模式后面的方法取代。
Cookbook > 3.x Migration Guide > 3.4 Migration Guide > Request & Response Deprecations
采用永恒回应
之前您迁移代码以使用新的响应方法,你 应该知道的概念上的差异,新方法都有。 不可变的方法通常使用with前缀表示。例如 ,
withLocation()
。由于这些方法在不可变的 上下文中操作,因此它们会返回需要分配给 变量或属性的新实例。如果你有一个看起来像控制器代码:$response = $this->response; $response->location('/login') $response->header('X-something', 'a value');
如果你简单地找到&取代你的代码会破坏方法名。 相反,你现在必须使用的代码看起来像:
$this->response = $this->response ->withLocation('/login') ->withHeader('X-something', 'a value');
有几个关键的不同:
更改的结果重新分配给
$this->response
。这是 以保持上述代码的意图。方法可以全部链接在一起。这允许您跳过所有中间对象的存储 。
Cookbook > 3.x Migration Guide > 3.4 Migration Guide > Adopting Immutable Responses
长话短说,你的情况,你必须返回不可改变的方法创建新的请求对象:
return $this->response
->withType('application/json');
->withStringBody($jsonSites);
如果您不会返回响应对象,那么您需要重新分配新的响应至$this->response
,如上面的引用中所述。
argghhhh!当然。如此愚蠢! – 2ndGAB