controller中重复代码是使用BaseController还是trait,或者?
1. 运行环境
1). 当前使用的 Laravel 版本?
Laravel 9
2). 当前使用的 php/php-fpm 版本?
PHP 版本:
8.1
2. 问题描述?
在多个controller中有大量重复代码,各位大佬是怎么操作的
use App\Models\Test;
class TestController extends Controller
{
/**
* Display a listing of the resource.
* @return View
*/
public function index(): View
{
return view('test.index')
->with('dicts', Test::dicts());
}
/**
* Display a listing of the resource.
* @return JsonResponse
*/
public function data(): JsonResponse
{
list($where, $offset, $limit) = search_param(request());
$query = Test::where('status', 1)->extWhere($where);
$list = $query->skip($offset)->limit($limit)->get();
return json($list, $query->count());
}
/**
* Show the form for creating a new resource.
* @return View
*/
public function create(): View
{
return view('test.create')->with('dicts', Test::dicts());
}
/**
* Store a newly created resource in storage.
* @return JsonResponse
*/
public function store(): JsonResponse
{
Test::create(request('af_row'))->save();
return succ();
}
/**
* Show the form for editing the specified resource.
*
* @param $id
* @return View
*/
public function edit($id): View
{
return view('test.edit')
->with('dicts', Test::dicts())
->with('item', Test::findOrFail($id));
}
/**
* Update the specified resource in storage.
* @return JsonResponse
*/
public function update(): JsonResponse
{
$data = Test::find(request('id'));
$data->fill(request('af_row'))->save();
return succ();
}
/**
* Remove the specified resource from storage.
* @param $id
* @return JsonResponse
*/
public function destroy($id): JsonResponse
{
return json(Test::destroy($id));
}
/**
* Display the specified resource.
* @param $id
* @return Response
*/
public function show($id): Response
{
return view('test.show')
->with('dicts', Test::dicts())
->with('item', Test::findOrFail($id));
}
}
如上,这是一个简单的curd的控制器,其中各个方法的内容大部分都是可以复用的,
只有视图名、模型名有变化,请问如何优雅的处理这些重复的代码,而不用反复的复制粘贴,修改模型名称?
目前我直接考虑了两种,BaseController或者trait,大概逻辑如下:
class BaseController extends Controller
{
protected $model ;
protected $viewPath = '';
/**
* Display a listing of the resource.
* @return View
*/
public function index(): View
{
return view($this->viewPath . 'index')
->with('dicts', $this->model::dicts());
}
}
trait Curd
{
protected $model ;
protected $viewPath = '';
/**
* Display a listing of the resource.
* @return View
*/
public function index(): View
{
return view($this->viewPath . 'index')
->with('dicts', $this->model::dicts());
}
}
class TestController extends BaseController
{
//不继承BaseController,使用trait
//use Curd;
protected $model ;
protected $viewPath = '';
public function __construct(Request $request)
{
$this->viewPath = 'test.';
$this->model = Test::class;
}
}
还有其他更优雅的处理方法吗?
推荐文章: