[英]How share code between application controllers using Laravel framework?
What is the best practice for distributing controllers code with Laravel? 使用Laravel分发控制器代码的最佳实践是什么?
Example: TaskController consumes particulary request and access specific model methods with task list as a result. 示例:TaskController使用特定请求并使用任务列表访问特定的模型方法。
OrganisationTaskTreeController consumes different request accessing same methods on Task Entity but also gets OrganisationTree resource with method shared with OrganisationController. OrganisationTaskTreeController使用不同的请求来访问任务实体上的相同方法,但是还通过与OrganisationController共享的方法获取OrganisationTree资源。
Code: 码:
class TaskController extends BaseController {
public function getTask(Request $request)
{
$_match = [];
if ($request->has('types'))
{
$_match['type'] = ['$in' => $request->get('types')];
}
if ( ! $request->has('group'))
{
throw new InvalidParameter("Undefined group parameter");
}
....
}
class OrganisationTaskTreeController extends BaseController {
public function getOrganizationTree(Request $request)
{
$_match = [];
$_tree = [];
if ($request->has('types'))
{
$_match['type'] = ['$in' => $request->get('types')];
}
if ( ! $request->has('group'))
{
throw new InvalidParameter("Undefined group parameter");
}
if ($request->has('unti'))
{
$_tree['unit'] = $request->get('unit');
}
....
}
} }
How not to duplicate this code? 如何不重复此代码?
I think Controllers should not be extended by design, because of using methods from many controllers. 我认为控制器不应该通过设计扩展,因为使用了许多控制器的方法。 It will be an overkill. 这将是一个过大的杀伤力。
I'm thinking about: 我在考虑:
Perhaps you could refactor the code you want to reuse to a method on a base class that the two classes can extend, eg class TaskController extends BaseController, BaseClass. 也许您可以将要重用的代码重构为两个类可以扩展的基类上的方法,例如TaskController扩展了BaseController,BaseClass。 Then you could use the method on every class that extends the BaseClass. 然后,您可以在扩展BaseClass的每个类上使用该方法。
How about a custom request object that you can typehint into whichever method that needs it for that specific validation? 您可以将自定义请求对象键入到用于特定验证所需的任何方法中,怎么样? https://www.laravel.com/docs/5.2/validation#form-request-validation https://www.laravel.com/docs/5.2/validation#form-request-validation
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.