Laravel 4 - Child constructor call parent constructor with dependency injection

后端 未结 6 1853
死守一世寂寞
死守一世寂寞 2021-02-05 02:53

I\'m building a CMS using Laravel 4 and I have a base admin controller for the admin pages that looks something like this:

class AdminController extends BaseCont         


        
6条回答
  •  爱一瞬间的悲伤
    2021-02-05 03:30

    There isn't a perfect solution and it's important to understand that this isn't an issue with Laravel itself.

    To manage this, you can do one of three things:

    1. Pass the necessary dependencies to the parent (which was your issue)

      // Parent
      public function __construct(UserAuthInterface $auth, MessagesInterface $message, ModuleManagerInterface $module)
      {
          $this->auth = $auth;
          $this->user = $this->auth->adminLoggedIn();
          $this->message = $message;
          $this->module = $module;
      }
      
      // Child
      public function __construct(UsersManager $user, UserAuthInterface $auth, MessagesInterface $message, ModuleManagerInterface $module)
      {
          $this->users = $users;
          parent::__construct($auth, $message, $module);
      }
      
    2. Auto resolve the dependencies in the parent construct as stated by @piotr_cz in his answer

    3. Create the instances in the parent construct instead of passing them as parameters (so you don't use Dependency Injection):

      // Parent
      public function __construct()
      {
          $this->auth = App::make('UserAuthInterface');
          $this->user = $this->auth->adminLoggedIn();
          $this->message = App::make('MessagesInterface');
          $this->module = App::make('ModuleManagerInterface');
      }
      
      // Child
      public function __construct(UsersManager $user)
      {
          $this->users = $users;
          parent::__construct();
      }
      

    If you want to test your classes, the third solution will be more difficult to test. I'm unsure if you can mock the classes using the second solution, but you mock them using the first solution.

提交回复
热议问题