Laravel:使用扩展控制器或Traits或其他东西?

时间:2017-11-01 15:30:00

标签: laravel laravel-5 laravel-5.5

为了维护我的Laravel应用程序并从许多重复的代码中保存自己,我已经提出了以下解决方案:

BaseController

class BaseController extends Controller
{ 
    public function get($id){
        return $this->baseService->get($id);
    }

    public function getAll(){
        return $this->baseService->getAll();
    }
}

BaseService

class BaseService
{
    protected $model;

    public function __construct($model){
        $this->model = $model;
    }

    public function get($id){
        return response()->json($this->model->where('id', $id)->first());
    }

    public function getAll()
    {
        return $this->model->get();
    } 
}

myController的

class MyController extends BaseController
{
    protected $model;
    protected $baseService;

    public function __construct(){
        $this->model= new Model();
        $this->baseService = new BaseService($this->model);
    }

    /**
     * This controller has all the functionality from BaseController now
     */
}

我想知道这是不是一个好方法。我应该坚持这个还是应该采用不同的方法?我听说过Traits但不确定他们是否在做同样的事情。它的Laravel 5.5我正在使用。

2 个答案:

答案 0 :(得分:1)

这是Trait的完美用例。特征用于可重用的功能。它们实施起来非常简单,并且不会花费几分钟的时间来改变你所拥有的东西。

以下是关于它们的精彩文章:https://www.conetix.com.au/blog/simple-guide-using-traits-laravel-5

答案 1 :(得分:1)

是的,traits用于定期将方法移出控制器。 Laravel框架使用的一个很好的例子是ThrottlesLogin特征。看看https://github.com/laravel/framework/blob/5.5/src/Illuminate/Foundation/Auth/ThrottlesLogins.php#L20 查看方法如何在控制器之外移动,但仍可通过使用use关键字导入特征来访问。

虽然特征适用于您的用例,但我不会在这里使用它们来实现您正在寻找的功能。我会使用存储库模式。它可以更好地分离您的代码并使其更具可重用性。

有关存储库模式的更多信息,请查看https://bosnadev.com/2015/03/07/using-repository-pattern-in-laravel-5/。基本上,您可以将代码分离到一个单独的存储库中,并使用内置在IoC中的Laravel将存储库注入控制器。

MyController

class MyController extends Controller
{
   protected $repo; 

   public function __construct(MyRepository $myRepository)
   {
     $this->repo = $myRepository;
   }

   public function index()
   {
      $myStuff = $this->repo->all();
   }

   // you can also inject the repository directly in the controller
   // actions.
   // look at https://laravel.com/docs/5.5/controllers#dependency-injection-and-controllers
   public function other(MyRepository $repo)
   {
       $myStuff = $repo->all();
   }
}