Creating Console command YII2

Creating Console command YII2


First we have to set starting script file. For web we have index.php but console we have yii in app root directory. Then manage console.php in config


#!/usr/bin/env php

<?php

// comment out the following two lines when deployed to production

defined('YII_DEBUG') or define('YII_DEBUG', true);

defined('YII_ENV') or define('YII_ENV', 'dev');

// fcgi doesn't have STDIN and STDOUT defined by default

defined('STDIN') or define('STDIN', fopen('php://stdin', 'r'));

defined('STDOUT') or define('STDOUT', fopen('php://stdout', 'w'));

define('YII2_FRAMEWORK_PATH_ABSOLUTE','{site absolute path}'); 

require 'constants.app.php';

require YII2_FRAMEWORK_PATH_ABSOLUTE . '/modules/common/config/config.common.php';

require YII2_FRAMEWORK_PATH_ABSOLUTE . '/modules/common/config/functions.common.php';

require YII2_FRAMEWORK_PATH_ABSOLUTE . '/vendor/autoload.php';

require YII2_FRAMEWORK_PATH_ABSOLUTE . '/vendor/yiisoft/yii2/Yii.php';

$config = require(__DIR__ . '/config/console.php');
$application = new yii\console\Application($config);
$exitCode = $application->run();
Create Module and follow steps
1) Your module should implements BootstrapInterface
class Module extends \yii\base\Module implements \yii\base\BootstrapInterface{
    public function bootstrap($app){
        if ($app instanceof \yii\console\Application) {
            $this->controllerNamespace = 'app\modules\my_module\commands';
        }
    }

}
2) Create your console controller in your module commands folder :
namespace app\modules\my_module\commands;

class ConsoleController extends \yii\console\Controller
{
    public function actionIndex()
    {
        echo "Hello World\n";
    }
}
3) Add your module to your app console configuration config/console.php :
'bootstrap' => [
    // ... other bootstrap components ...
    'my_module',
],
'modules' => [
    // ... other modules ...
    'my_module' => [
        'class' => 'app\modules\my_module\Module',
    ],
],
4) You can now use your command :
yii my_module/console/index
REFERENCE 
https://stackoverflow.com/questions/32711006/how-to-create-console-command-in-a-module

Share this

Related Posts

Previous
Next Post »