简体   繁体   English

在Laravel中动态注册命令

[英]Dynamically Register Commands in Laravel

I am able to register Events programmatically Illuminate\\Support\\Facades\\Event and it's listener method. 我能够以编程方式注册事件Illuminate\\Support\\Facades\\Event及其侦听器方法。 I would like to register command dynamically a similar way. 我想以类似的方式动态注册命令。 Is there a way to do it in Laravel? Laravel有办法做到吗? Or what is the best way of doing in Laravel except for registering it inside app/Console/Kernel.php ? 或者,除了在app/Console/Kernel.php注册之外,在Laravel中做的最好方法是什么?

Update I am able to register a single class via the following code. 更新我可以通过以下代码注册一个类。


use Illuminate\Console\Application as Artisan;

if (app()->runningInConsole()) {
    Artisan::starting(function ($artisan) use ($commandClass) {
        $artisan->resolveCommands($commandClass);
    });
}

If you look into your app/Console/Kernel.php you should see a statement like this: 如果查看您的app/Console/Kernel.php您应该会看到类似以下的语句:

$this->load(__DIR__.'/Commands');

This means that all command classes saved in app/Console/Commands/ will be automatically loaded and registered. 这意味着保存在app/Console/Commands/中的所有命令类将被自动加载和注册。 Furthermore, if you create a command using artisan, Ex: php artisan make:command MyCommand , the class will be stored in app/Console/Commands/MyCommand.php . 此外,如果您使用artisan创建命令,例如: php artisan make:command MyCommand ,则该类将存储在app/Console/Commands/MyCommand.php

While method provided by Pablo could be a better option for a single directory but if you have commands spread across different namespaces and directories one may end up adding multiple entries in app/Console/Kernel.php 虽然Pablo提供的方法对于单个目录可能是一个更好的选择,但是如果您将命令分布在不同的命名空间和目录中,则可能最终会在app / Console / Kernel.php中添加多个条目

In my use case the $commandClass is pulled from multiple xml files spread across multiple composer packages, therefore, I had to use this approach: 在我的用例中, $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);
    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM