如何将依赖项注入laravel作业

时间:2015-10-31 23:17:31

标签: php laravel laravel-5 laravel-5.1

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

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

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

我有这个,但它不起作用

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

2 个答案:

答案 0 :(得分:23)

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

答案 1 :(得分:2)

万一有人想知道如何将依赖项注入handle函数中

在服务提供商中输入以下内容

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

laravel documentation for job