Source

Laraval Queues dependency injection

The first thing we need to know about Laravel Queues is that the dependency injection cannot happen in the constructor and it happens handle method level.

When the job is being processed by the queue, the handle method is invoked and we are able to type-hint dependencies on the method of the job and the Laravel Service Container automatically injects these dependencies.

Note: If you want to control this fully, you can go into App\Providers\AppServiceProvider, in the boot method, and use the bindMethod method. The bindMethod accepts a callback which receives the job and the container.
Within this callback, you are free to invoke the handle method however you want.

use App\Jobs\MyJob;
use App\Services\MyService;
use App\Repositories\MyRepository;
$this->app->bindMethod([MyJob::class, 'handle'], function ($job, $app) {
return $job->handle(
$app->make(MyService::class),
$app->make(MyRepository::class), ... more classes
);
});

The handle injection nuisance

When we inject the classes through the handle method we do not define them as class properties, therefore when we need them in other functions inside the Job (Considering it will get substantially complex and big and your logic is split in multiple methods) we will have to pass them as parameters to said functions.

And I have a way that you can avoid this and keep your code a little bit tidier.

class MyJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

private something $data;
private MyService $service;
private MyRepo $repo;
public function __construct(something $data)
{
$this->data = $data;
}


public function handle(MyService $service, MyRepo $repo)
{
$this->service = $service;
$this->repo = $repo;
}
private function doStuff()
{
$stuff = $this->service->processStuff();
$this->repo->saveStuff($stuff);
}
}

And just like so we do not need to pass anything as parameters for any amount of functions you have.

Note: I have been dealing with jobs with hundreds of lines lately and this has been bugging me initially, this has helped me so I hope it helps you too!

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store