Yii2: run console command from controller in vendor directory

I am refactoring our large production application. This includes splitting some of the tools I've built, such as the schema / semantics migration tool for the command line, into their own repositories to be used by multiple applications.

If it's in the console / controllers, it gets picked up. If I push them to my repository and require it through Composer, how do I know Yii when I say php yii db/up

I want to go to new\vendor\namespace\DbController@actionup

?

+3


source to share


1 answer


If you create an extension (and load it through composer, of course) you can find Module.php

inside that will contain the path to the console controllers (which you can call with your terminal).

I'll write my example for a namespace common\modules\commander

, for a provider extension your namespace will be different, but it works the same for everyone. So I have the following file structure for my extension

<app>
  common
    modules
      commander
        controllersTestController.phpModule.php

      

My module class looks like this:

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

inherits from 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 for everything to work is to register the Module.php in the settings console/config/main.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 will print to you 123

showing that everything is working and the console controllers are located in different folders!

+2


source







All Articles