T
T
tigra2020-08-06 13:33:45
Laravel
tigra, 2020-08-06 13:33:45

What is the correct way to inject dependencies in laravel controller?

There was a dispute about where it is more correct to specify dependencies in the Laravel controller?
in __construct

ClassController extends Controller {
   private $d1;
   private $d2;
   private $d3;

   public function __construct(Dependency1 $d1, Dependency2 $d2, Dependency3 $d3) {
       $this->d1 = $d1;
       $this->d2 = $d2;
       $this->d3 = $d3;       
   }

   public function create() {
        $this->d1->send();
        $this->d2->send();
     }

     public function index() {
       $this->d3->send();
     }
}

Or in the methods themselves?
ClassController extends Controller {
     public function create(Dependency1 $d1, Dependency2 $d2) {
        $d1->send();
        $d2->send();
     }

     public function index(Dependency3 $d3) {
       $d3->send();
     }
}

How correct is it to specify dependencies for the entire class that won't be used everywhere? I expect laravel to pull only those dependencies that I specify in the method. Or does it not work like that and it will still work the same as if I specified it in __construct?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question