简体   繁体   English

Yii2:从供应商目录中的控制器运行控制台命令

[英]Yii2: run console command from controller in vendor directory

I am doing some refactoring of our large work app. 我正在做一些重构我们的大型工作应用程序。 This involves separating out some tools I've build, like a schema/seed migration tool for the command line, in to their own repositories to be used by multiple applications. 这涉及将我构建的一些工具(如命令行的模式/种子迁移工具)分离到他们自己的存储库以供多个应用程序使用。

If it's in console/controllers, it gets picked up. 如果它在控制台/控制器中,它会被拾取。 If I move them to their own repository and require it via Composer, how do I get Yii to know when I say php yii db/up , i mean go to the new\\vendor\\namespace\\DbController@actionup ? 如果我将它们移动到他们自己的存储库并通过Composer需要它,我如何让Yii知道我什么时候说php yii db/up ,我的意思是去new\\vendor\\namespace\\DbController@actionup

If you create an extension (and load it through composer of course), you can locate Module.php inside, which will hold path to console controllers (that you can call with your terminal). 如果你创建一个扩展(当然是通过composer加载),你可以在里面找到Module.php ,它将保存控制台控制器的路径(你可以用你的终端调用)。

I will write my example for common\\modules\\commander namespace, for vendor extension your namespace will differ, but it work for all of them the same way. 我将为common\\modules\\commander命名空间编写我的示例,对于供应商扩展,您的命名空间将有所不同,但它以相同的方式适用于所有这些。 So I have the following file structure for my extension 所以我的扩展程序有以下文件结构

<app>
  common
    modules
      commander
        controllers
          • TestController.php
        • Module.php

My Module class looks as follow: 我的Module类看起来如下:

namespace common\modules\commander;
use yii\base\Module as BaseModule;
class Module extends BaseModule
{
    public $controllerNamespace = 'common\modules\commander\controllers';

    public function init()
    {
        parent::init();
    }
}

And TestController.php is inherited from yii\\console\\Controller : TestController.php继承自yii\\console\\Controller

namespace common\modules\commander\controllers;
use yii\console\Controller;
class TestController extends Controller
{
    public function actionIndex()
    {
        echo 123;
    }
}

And the main part to make everything work is to register out Module.php in console/config/main.php settings 使一切正常工作的主要部分是在console/config/main.php设置中注册Module.php

'modules' => [
    'commander' => [
        'class' => \common\modules\commander\Module::className(),
    ],
    ...
],

Here it is, now you can use your command like: 现在,您可以使用以下命令:

yii commander/test/index

And it'll print you 123 , showing that everything works and Console Controllers are located in different folders! 它会打印123 ,显示一切正常,控制台控制器位于不同的文件夹中!

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

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