我能够以编程方式Illuminate\Support\Facades\Event
注册事件,它是侦听器方法。我想以类似的方式动态注册命令。 Laravel有办法做到吗?或者,除了在app/Console/Kernel.php
中注册之外,在Laravel中做的最好的方法是什么?
更新 我可以通过以下代码注册一个类。
use Illuminate\Console\Application as Artisan;
if (app()->runningInConsole()) {
Artisan::starting(function ($artisan) use ($commandClass) {
$artisan->resolveCommands($commandClass);
});
}
答案 0 :(得分:1)
如果您查看app/Console/Kernel.php
,应该会看到类似这样的语句:
$this->load(__DIR__.'/Commands');
这意味着保存在app/Console/Commands/
中的所有命令类将被自动加载和注册。此外,如果您使用工匠创建命令,例如:php artisan make:command MyCommand
,则该类将存储在app/Console/Commands/MyCommand.php
中。
答案 1 :(得分:0)
虽然Pablo提供的方法对于单个目录可能是一个更好的选择,但是如果您将命令分散在不同的名称空间和目录中,则可能最终会在app / Console / Kernel.php中添加多个条目
在我的用例中,$commandClass
是从散布在多个作曲者程序包中的多个xml文件中提取的,因此,我不得不使用这种方法:
use Illuminate\Console\Application as Artisan;
// fetch command classes from different sources and register it here.
if (app()->runningInConsole()) {
Artisan::starting(function ($artisan) use ($commandClass) {
$artisan->resolveCommands($commandClass);
});
}