回复不了代码,我是说一下吧。因为时间过去的有点久了,不太记得了。我做了一个Trait,在BaseController里引入,这个Trait叫Responder,封装了Dingo API的响应数据,加入status_code和message
trait Responder
{
use Helpers;
public function responseCollection(Collection $collection, TransformerAbstract $transformer)
{
return $this->response->collection($collection, $transformer, [], function ($resource, Manager $fractal) {
$fractal->setSerializer(new CustomSerializer());
});
}
public function responseItem($item, TransformerAbstract $transformer)
{
return $this->response->item($item, $transformer, [], function ($resource, Manager $fractal) {
$fractal->setSerializer(new CustomSerializer());
});
}
public function responsePaginate(Paginator $paginator, TransformerAbstract $transformer)
{
return $this->response->paginator($paginator, $transformer, [], function ($resource, Manager $fractal) {
$fractal->setSerializer(new CustomSerializer());
});
}
public function responseData(array $data)
{
return Response::json([
'message' => '操作成功',
'status_code' => 200,
'data' => $data
], 200);
}
public function responseSuccess($message='操作成功')
{
return Response::json([
'message' => $message,
'status_code' => 200
], 200);
}
public function responseFailed($message='操作失败')
{
return Response::json([
'message' => $message,
'status_code' => 400
], 400);
}
public function responseError($message='未知错误')
{
return Response::json([
'message' => $message,
'status_code' => 500
], 500);
}
}