我想更新我定义的资源之一(用户)以更新他的当前状态(在线/离线)和/或位置。因此,我会使用这样的 PUT 请求:
PUT http://server/v1/users/12345
有效载荷
{
"status": 0
}
例如,将状态设置为离线。
或者可能是:
有效载荷
{
"latitude": 100,
"longitude": 100
}
后端基于 Laravel/PHP,我在控制器中响应此请求:
public function update(Request $request, $userReference) {
// Get payload from request
$bodyContent = json_decode($request->getContent(), true);
$userReference = $userReference;
// Update the user location
$updateResponderLocationCommand = new UpdateResponderLocationCommand($bodyContent);
$this->commandBus->execute($updateResponderLocationCommand);
$response = [
'userReference' => $userReference
];
return $this->setStatusCode(201)->respond($response);
}
该控制器使用我集成的命令系统,该系统将触发执行更新的任务。
我的问题是,我在哪里挣扎:
- 如何区分应执行的命令。目前,只有位置更新在此方法中。但我不想只为状态更新编写新的更新消息。
- 那么请求需要如何正常工作呢?我是否仍然可以将该方法与
PUT http://server/v1/user/100
一起使用,并通过在有效负载中使用关键字和选择开关 - 控制器中的方法来区分要执行的任务? - 当我只更新单个组件时,我是否完全可以使用 PUT?我读到我应该改用 POST 吗?
- 通常,相应的操作将通过路由机制发送。我们将在您的
json object
上有一个与应该发生的函数相对应的action
属性。
让我们来看看:
public function update(....){
switch($request->get('action'))
{
case 'location':
//execute the command here
break;
case 'status':
//execute the command here
break;
}
}
通过这种方式,我们可以确保我们的commands
是根据我们的行动调度的。这是我更喜欢的方法。
关于整个 put v.s. 帖子 - 没有理由再写一篇文章,因为这个问题线程在这里有迄今为止最好的细分和解释。
您应该参考#2中的链接。创建资源时,应使用
PUT
。这可确保请求是幂等的并且不会重复(客户端挂起、服务器瓶颈等)。