What is dependency injection ??
If you want to use any functionality or components in your controller like send mail ,you register that class in controller and then create its object in every function but when we want that functionality in every function or methods of controller then you use dependency injection
Create dependency injection ,follow steps -
-
Register component
Register that component class using - use Class eg- use Mailer;
-
Create variable in class and initialize it in constructor as follow :
protected $mailer; public function __construct(Mailer $mailer) { $this->mailer = $mailer; }
Here, now depenedncy is injected in constructor and we access it using $this->mailer; Dependency can be anyclass even model,like -protected $user; public function __construct(User $user) { $this->user = $user; }
,now we dont need to create model object in function likepublic function store() { $user= new User; }
we do it as -public function store() { $user= $this->user; $user->name='ABC'; $user->save(); }