YII2: Create console commands inside a module or extension

You are viewing revision #6 of this wiki article.
This version may not be up to date with the latest version.
You may want to view the differences to the latest version or see the changes made in this revision.

« previous (#5)next (#7) »

Here is a small guide how to get console commands running inside modules & extensions. For this guide I used a fresh yii2 basic application template.

1) Create a new module in your application.
(I named it "example_commands" for this instructions)

Generate new module from commandline with gii (or use gii-webinterface)

command> yii gii/module --moduleID=example_commands --moduleClass=app\modules\example_commands\Module

Running 'Module Generator'...

The following files will be generated:
        [new] modules\example_commands.php
        [new] modules\controllers\DefaultController.php
        [new] modules\views\default\index.php

Ready to generate the selected files? (yes|no) [yes]:y

2) Edit the Module.php
app/modules/example_commands/Module.php

namespace app\modules\example_commands;

use Yii;
use yii\base\BootstrapInterface;
use yii\base\Module as BaseModule;

class Module extends BaseModule implements BootstrapInterface
{
    public $controllerNamespace = 'app\modules\example_commands\controllers';

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

    public function bootstrap($app)
    {
        if ($app instanceof \yii\console\Application) {
        	$this->controllerNamespace = 'app\modules\example_commands\commands';
        }
    }
}
[/code]

3) Create your folder & command class inside your module:
app/modules/example_commands/commands/TestingController.php

namespace app\modules\example_commands\commands;

use yii\console\Controller;
use yii\helpers\Console;

class TestingController extends Controller
{
    public function actionIndex($message = 'hello world from module')
    {
        echo $message . "\n";
    }
}

4) Add your module to app configurations:
app/config/console.php

'bootstrap' => [
    // ... other bootstrap components ...
    'example_commands'
],
'modules' => [
    // ... other modules ...
    'example_commands' => [
        'class' => 'app\modules\example_commands\Module',
    ],
],

Don't forget app/config/web.php if you have non-console stuff in your module / extension.

5) That was it - you can use your command now like:
moduleId/controller/action

command>yii example_commands/testing/index
hello world from module
8 0
6 followers
Viewed: 64 099 times
Version: Unknown (update)
Category: Tutorials
Written by: MetaCrawler
Last updated by: Luis Armando
Created on: Aug 6, 2015
Last updated: 5 years ago
Update Article

Revisions

View all history

Related Articles