Yii2 Console Commands

Yii2 provides a robust console application that allows developers to run scripts from the command line. These commands are useful for tasks such as database migrations, cron jobs, background tasks, and system maintenance.

This tutorial covers:

  • Creating custom console commands
  • Running console commands in Yii2 Basic & Advanced templates
  • Module-level console command integration

1. Creating Custom Console Commands in Yii2

A Yii2 console command is a class that extends yii\console\Controller. These commands reside in the commands folder inside console for the Basic template and inside yii/console/controllers for the Advanced template.

1.1 Basic Structure of a Console Command

To create a custom console command:

Step 1: Create a Command File

In Basic Template, create the file app/commands/HelloController.php.
In Advanced Template, create the file console/controllers/HelloController.php.

namespace app\commands; // For Basic
// namespace console\controllers; // For Advanced

use yii\console\Controller;
use yii\console\ExitCode;

class HelloController extends Controller
{
    public function actionIndex()
    {
        echo "Hello from Yii2 Console!\n";
        return ExitCode::OK;
    }

    public function actionGreet($name = "Guest")
    {
        echo "Hello, $name!\n";
        return ExitCode::OK;
    }
}

1.2 Running the Console Command

To execute the command, open the terminal and navigate to your Yii2 project root directory.

Run the index action:

php yii hello

Run the greet action with a name:

php yii hello/greet John

Output:

Hello, John!

2. Registering Console Commands in a Yii2 Module

In Yii2, console commands can be added at the module level. This is useful when you want to separate console logic by modules.

2.1 Creating a Module-Level Console Command

Let’s say we have a module called dashboard. We want to add a console command under this module.

Step 1: Create the Module

Create a module at modules/dashboard/Module.php:

namespace app\modules\dashboard;

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

class Module extends BaseModule
{
    public function init()
    {
        parent::init();

        // Register console commands only in console requests
        if (Yii::$app->request->isConsoleRequest) {
            \Yii::configure($this, ['controllerNamespace' => 'app\modules\dashboard\commands']);
        }
    }
}

Step 2: Create the Console Command

Create modules/dashboard/commands/DashboardController.php:

namespace app\modules\dashboard\commands;

use yii\console\Controller;
use yii\console\ExitCode;

class DashboardController extends Controller
{
    public function actionStats()
    {
        echo "Fetching dashboard statistics...\n";
        return ExitCode::OK;
    }
}

Step 3: Register the Module in console.php

In the Basic Template, add the module to config/console.php:

return [
    'id' => 'yii-console',
    'basePath' => dirname(__DIR__),
    'bootstrap' => ['dashboard'], // Register module
    'modules' => [
        'dashboard' => [
            'class' => 'app\modules\dashboard\Module',
        ],
    ],
];

Step 4: Run the Module Console Command

php yii dashboard/stats

Output:

Fetching dashboard statistics...

3. Console Commands in Yii2 Advanced Template

In the Advanced Template, console commands are stored in console/controllers. They work similarly to the Basic template but with a different directory structure.

Step 1: Create a Console Command

Create console/controllers/UserController.php:

namespace console\controllers;

use yii\console\Controller;
use yii\console\ExitCode;
use common\models\User;

class UserController extends Controller
{
    public function actionList()
    {
        $users = User::find()->all();
        foreach ($users as $user) {
            echo $user->username . "\n";
        }
        return ExitCode::OK;
    }
}

Step 2: Run the Console Command

php yii user/list

4. Best Practices for Yii2 Console Commands

  • Always return ExitCode::OK (0) for successful execution
  • Use arguments and options to make commands more dynamic
  • Secure console commands – avoid running destructive actions by mistake
  • Log outputs for debugging – use Yii::info() for logs

Conclusion

Yii2 provides a powerful console application framework that allows developers to create efficient command-line scripts. Whether you're using the Basic or Advanced template, or integrating commands at the module level, Yii2 makes it simple to run tasks via CLI.