Search code examples
yii2yii2-extensionyii2-module

Yii2: How to create module commands without controller name?


There was a similar question asking "how to create console command in a module?" which contains a good answer on how to add commands to your Yii2 modules.

However, the resulting commands must be in the following format:

./yii module_name/command/sub-command

where command corresponds with the console Controller name, and sub-command corresponds with its Action names.

How do we omit the controller name and have it list action names only so that our commands will be in the following format:

./yii module_name/command


Solution

  • I'm not sure what is the purpose of dividing console commands to modules, and hiding controller name (like making it a DefaultController).

    But anyway, one of the possible solutions is to configure controllerMap in config\console.php file (considering you are using a basic template).

    $config = [
        'id' => 'basic-console',
        ...
        'controllerMap' => [
            'module_name' => [
                'class' => 'app\modules\module_name\commands\ConsoleController',
            ],
        ],
        ...
    ];
    

    So now when you run php yii module_name/<action_name>, it calls directly ConsoleController actions

    ..so i.e. php yii module_name/index results to module_name\ConsoleController->actionIndex() method