How to add new console commands

bolty

Member
Hello
I'm building an extension to migrate my customer data from my existing EMA (interspire) into MailWizz. I have too many customers to do this manually.

I need to run my import task via cron and I'm wondering if my extension can add a command to console.php? If so how is this done?
 
@bolty - it's totally possible to register commands from command line.
In the run() method of the extension, you could do this:
PHP:
Yii::app()->commandMap['your-command-name'] = [
    'class'=>'ext-YOUR_EXT_NAME.console..commands.MySuperCommand',
];
( https://www.yiiframework.com/doc/api/1.1/CConsoleApplication#commandMap-detail )

MySuperCommand must be a class, an instance of ConsoleCommand command, see:
https://www.yiiframework.com/doc/guide/1.1/en/topics.console

So the file will look like:
PHP:
<?php defined('MW_PATH') || exit('No direct script access allowed');

class MySuperCommand extends ConsoleCommand 
{
    public function actionIndex() 
    {
        echo 'Hello World!' . "\n";
    }
}

Next, in the cron jobs, you can add a command like:
Code:
* * * * * php /absolute/path/to/apps/console/console.php your-command-name >/dev/null 2 >&1
 
Just updating this thread incase anyone else wants to create a console command from an extension.
The solution was actually to add this in the extensions run() method:

PHP:
if ($this->isAppName('console')) {
            Yii::app()->getCommandRunner()->commands['your-command-name'] = [
                'class'        =>'ext-YOUR_EXT_NAME.console.commands.MySuperCommand',
            ];
}

The reason you have to use Yii::app()->getCommandRunner()->commands not Yii::app()->commandMap is because by the time the run method of your extension is called CConsoleApplication has already passed the commandMap to CConsoleCommandRunner so it's too late to change the commandMap there

Cheers
 
Back
Top