我正在从我的控制器中添加一个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;
}
}
答案 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));
});