I'm adding a laravel job to my queue from my controller as such
$this->dispatchFromArray( 'ExportCustomersSearchJob', [ 'userId' => $id, 'clientId' => $clientId ] );
I would like to inject the userRepository
as a dependency when implementing the ExportCustomersSearchJob
class. Please how can I do that?
I have this but it doesn't work
class ExportCustomersSearchJob extends Job implements SelfHandling, ShouldQueue { use InteractsWithQueue, SerializesModels, DispatchesJobs; private $userId; private $clientId; private $userRepository; /** * Create a new job instance. * * @return void */ public function __construct($userId, $clientId, $userRepository) { $this->userId = $userId; $this->clientId = $clientId; $this->userRepository = $userRepository; } }
In Laravel, dependency injection is the process of injecting class dependencies into a class through a constructor or setter method. This allows your code to look clean and run faster. Dependency injection involves the use of a Laravel service container, a container that is used to manage class dependencies.
Types of Dependency Injection The injector class injects dependencies broadly in three ways: through a constructor, through a property, or through a method. Constructor Injection: In the constructor injection, the injector supplies the service (dependency) through the client class constructor.
Dependency injection is a procedure where one object supplies the dependencies of another object. Dependency Injection is a software design approach that allows avoiding hard-coding dependencies and makes it possible to change the dependencies both at runtime and compile time.
The Laravel inversion of control container is a powerful tool for managing class dependencies. Dependency injection is a method of removing hard-coded class dependencies. Instead, the dependencies are injected at run-time, allowing for greater flexibility as dependency implementations may be swapped easily.
You inject your dependencies in the handle
method:
class ExportCustomersSearchJob extends Job implements SelfHandling, ShouldQueue { use InteractsWithQueue, SerializesModels, DispatchesJobs; private $userId; private $clientId; public function __construct($userId, $clientId) { $this->userId = $userId; $this->clientId = $clientId; } public function handle(UserRepository $repository) { // use $repository here... } }
In case anyone is wondering how to inject dependency into handle
function:
put the following in a service provider
$this->app->bindMethod(ExportCustomersSearchJob::class.'@handle', function ($job, $app) { return $job->handle($app->make(UserRepository::class)); });
laravel documentation for job
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With