如何将依赖项注入 Laravel 作业

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33457639/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 12:36:09  来源:igfitidea点击:

How to inject dependencies to a laravel job

phplaravellaravel-5laravel-5.1

提问by Arnold Ewin

I'm adding a laravel job to my queue from my controller as such

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

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

I would like to inject the userRepositoryas a dependency when implementing the ExportCustomersSearchJobclass. Please how can I do that?

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

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

回答by Joseph Silber

You inject your dependencies in the handlemethod:

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

回答by m_____ilk

In case anyone is wondering how to inject dependency into handlefunction:

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

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

工作的 Laravel 文档