【发布时间】:2020-01-28 20:25:12
【问题描述】:
在 laravel API 资源中:
我需要一种动态方法来概括所有控制器中要使用的所有资源的代码,而不是在每个控制器的所有方法中使用资源。为了更清楚,我有一个特征,包括返回 json 响应的通用函数数据和状态码,让我们来一个“示例函数”假设它是 showAll(Collection $collection) 用于返回指定模型的数据集合,例如它用于返回所有用户数据 .. 所以我需要构建一个函数来调用指定模型的任何资源,因为我知道我有很多模型......
a) 包含 showAll 方法的特征:
namespace App\Traits;
use Illuminate\Support\Collection;
trait ApiResponser
{
private function successResponse($data, $code) {
return response()->json($data, $code);
}
protected function showAll(Collection $collection, $code = 200) {
$collection = $this->resourceData($collection);
$collection = $this->filterData($collection);
$collection = $this->sortData($collection);
$collection = $this->paginate($collection);
$collection = $this->cacheResponse($collection);
return $this->successResponse([$collection, 'code' => $code], $code);
}
protected function resourceData(Collection $collection) {
return $collection;
}
}
b) 用户控制器作为示例
namespace App\Http\Controllers\User;
use App\User;
use Illuminate\Http\Request;
use App\Http\Controllers\ApiController;
class UserController extends ApiController
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$users = User::all();
// Here the showAll(Collection $collection) is used
return $this->showAll($users);
}
}
c) 用户资源:
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class UserResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return [
'identity' => $this->id,
'name' => $this->name,
'email' => $this->email,
'isVerified' => $this->verified,
'isAdmin' => $this->admin,
'createDate' => $this->created_at,
'updateDate' => $this->updated_at,
'deleteDate' => $this->deleted_at,
];
}
}
generalize:表示在任何地方都使用,没有代码冗余
【问题讨论】: