Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to create console command in a module?

Tags:

yii2

console command, like ./yii hello/world.

I'm using yii-app-basic.

what I want is not create console command in the dir commands/ but in a module.

like image 883
haoliang Avatar asked Sep 22 '15 07:09

haoliang


2 Answers

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
like image 156
soju Avatar answered Sep 22 '22 11:09

soju


Here is a good Tutorial and Discussion.

Follow Below Steps on Tutorial:

1) Create a new module in your application. 
2) Edit the Module.php. 
3) Create your folder and command inside your module. 
4) Add your module to app configurations.
like image 44
Insane Skull Avatar answered Sep 18 '22 11:09

Insane Skull