如何使用Laravel框架在应用程序控制器之间共享代码?

What is the best practice for distributing controllers code with Laravel?

Example: TaskController consumes particulary request and access specific model methods with task list as a result.

OrganisationTaskTreeController consumes different request accessing same methods on Task Entity but also gets OrganisationTree resource with method shared with OrganisationController.

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:

  • Traits
  • HMVC
  • Controller as Service
  • or will it be good to make a Respository which consumes $request?

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. Then you could use the method on every class that extends the 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