如何为laravel作业注入依赖项


How to inject dependencies to a laravel job

我正在从控制器向队列添加一个laravel作业,例如

$this->dispatchFromArray(
    'ExportCustomersSearchJob',
    [
        'userId' => $id,
        'clientId' => $clientId
    ]
);

我想在实现ExportCustomersSearchJob类时将userRepository作为依赖项注入。请问我该怎么做?

我有这个,但它不起作用

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;
    }
}

handle方法中注入依赖项:

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...
    }
}

如果有人想知道如何将依赖项注入handle函数:

将以下内容放入服务提供商

$this->app->bindMethod(ExportCustomersSearchJob::class.'@handle', function ($job, $app) {
    return $job->handle($app->make(UserRepository::class));
});

作业的laravel文档

Laravel v5及更高版本

自Laravel v5以来,作业中的依赖关系由它们自己处理。文档显示

"您可以在handle方法上键入hint所需的任何依赖项,服务容器将自动注入它们";

因此,现在,在Job的handle方法中,您所要做的就是添加要使用的依赖项。例如:

use From/where/ever/UserRepository;
class test implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    public function __construct()
    {
//
    }
    public function handle(UserRepository $userRepository)
    {
//        $userRepository can be used now.
    }
}