how to create console command in a module?

2019-04-28 06:30发布

问题:

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.

回答1:

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


回答2:

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.


标签: yii2