我有我如何能改善这种“加行动”的一些问题(方法):我使用的是add
动作只有在POST请求:CakePHP的添加操作在“控制器”返回JSON
1日。这是正确的 ?
第2张:这action
没有意见($this->autoRender = false;
)。这是正确的 ?
3:我设置以.json文件针对这一action
但我没有航线上改变路由以.json文件(该文件将被返回的时候访问本地主机:8765 /用户/加)。这是正确的 ?
4th:我使用Enums
(手工制作)存储将返回给用户的消息。这是正确的 ?
第五:我使用的对象来存储消息的字段(这将返回给用户)时,该对象将被序列化,并返回这样的:
$this->response->body(json_encode($response)); // It's correct ?
控制器代码:
public function add()
{
$this->autoRender = false;
$this->response->type('json');
$user = $this->Users->newEntity();
if ($this->request->is('post')) {
$user = $this->Users->patchEntity($user, $this->request->data);
if ($this->Users->save($user)) {
$this->Auth->setUser($user->toArray());
$response = new ResponseMessage();
$response->code = CodeEnum::USER_ADDED;
$response->name = NameEnum::USER_ADDED;
$response->type = TypeMessageEnum::SUCCESS;
$this->response->body(json_encode($response));
} else {
$response = new ResponseMessage();
$response->code = CodeEnum::USER_NOT_ADDED;
$response->name = NameEnum::USER_NOT_ADDED;
$response->type = TypeMessageEnum::ERROR;
$this->response->body(json_encode($response));
}
}
}
[更新]
我把我的这个控制器上:
$this->set('response', $response);
$this->set('_serialize', ['response']);
但返回此JSON:
{response: {code: 1, name: "Login efetuado com sucesso.", message: null, type: "Sucesso"}}
,但只能被退回:
{code: 1, name: "Login efetuado com sucesso.", message: null, type: "Sucesso"}
我用正确的代码和新问题更新我的答案。 – Ricardo
更改'$ this-> set('_ serialize',['response']); '到'$ this-> set('_ serialize','response'); ' – ADmad