从命令调度作业时无法实例化接口



我在我的Laravel应用程序中编写了一个自定义工匠命令,它调度了一个作业。该作业在其handle()方法中具有服务依赖关系,该方法通过 Laravel 的 DI 机制解决。正常运行应用程序时,依赖项已正确注入,但是,当我尝试从终端运行php artisan my:command时,出现如下错误:

Symfony\Component\Debug\Exception\FatalThrowableError(code: 0): 无法实例化接口 App\Services\ABCInterface at/Users/john/code/laravel-project/app/Providers/ABCServiceProvider.php:28)

这是我register()ABCServiceProvider方法(另请阅读评论):

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

另外,如果我将依赖项(类型提示)注入命令类的handle()方法,laravel可以解决它。只是 Job 类的 handle() 方法无法解决依赖关系。

为什么在正常应用程序流中解析绑定类,但在运行命令时无法解析?我该如何解决这个问题?

由于作业的handle函数已在队列中解析,请尝试重新启动队列工作线程。

对代码进行更改后,必须重新启动队列工作线程才能使更改在队列上生效。

请记住,队列工作线程是长期进程,将启动的应用程序状态存储在内存中。因此,它们在启动后不会注意到代码库中的更改。因此,在部署过程中,请务必重新启动队列工作线程。

查看文档。

最新更新