我在Laravel应用中编写了一个自定义工匠命令,该命令可以调度一个Job。该作业的handle()
方法具有服务依赖性,可通过Laravel的DI机制来解决。正常运行应用程序时,依赖项已正确注入,但是,当我尝试从终端运行php artisan my:command
时,出现如下错误:
Symfony \ Component \ Debug \ Exception \ FatalThrowableError(代码:0):无法在/Users/john/code/laravel-project/app/Providers/ABCServiceProvider.php:28)实例化接口App \ Services \ ABCInterface >
这是我的register()
的{{1}}方法(也请阅读注释):
ABCServiceProvider
要调度的Job的public function register()
{
$this->app->bind(ABCInterface::class, function ($app) {
if ($app->environment(['testing', 'local'])) {
// The following log statement is executed when the app runs normally.
// But isn't executed when the artisan command is run from the console.
\Log::debug('Instantiating FakeABCService');
// The following class implements ABCInterface.
return new FakeABCService;
} else {
// The following class implements ABCInterface.
return new ABCService;
}
});
}
方法:
handle()
最后,工匠命令类的public function handle(ABCInterface $abcService)
{
//
}
方法:
handle()
此外,如果我将依赖项(类型提示)注入到命令类的/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
$post = Post::first();
if ($this->confirm("Are you sure?")) {
MyJob::dispatch($post);
$this->comment('Done!');
return;
}
}
方法中,laravel可以解决它。只是Job类的handle()方法无法解决依赖关系。
为什么在正常的应用程序流程中正在解析绑定的类,但是在运行命令时却无法解析呢?我该如何解决?
答案 0 :(得分:0)
由于在队列中解析了作业的handle
函数,请尝试重新启动队列工作器。
对代码进行更改后,必须重新启动队列工作器才能使更改在队列上生效。
请记住,队列工作器是长期存在的进程,并将启动的应用程序状态存储在内存中。因此,启动它们后,他们将不会注意到代码库中的更改。因此,在部署过程中,请确保重新启动队列工作器。