如何将依赖项注入 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
How to inject dependencies to a laravel job
提问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 userRepository
as a dependency when implementing the ExportCustomersSearchJob
class. 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 handle
method:
您在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 handle
function:
如果有人想知道如何将依赖注入到handle
函数中:
put the following in a service provider
将以下内容放入服务提供者中
$this->app->bindMethod(ExportCustomersSearchJob::class.'@handle', function ($job, $app) {
return $job->handle($app->make(UserRepository::class));
});