如何将依赖项注入到 laravel 作业

2022-08-30 14:29:59

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

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

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

我有这个,但它不起作用

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

答案 1

在方法中注入依赖项: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...
    }
}

答案 2

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

将以下内容放在服务提供商中

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

工作文档


推荐