
A Yii2 console application is a CLI-based program that runs PHP scripts outside the web server, enabling background tasks, scheduled jobs, and maintenance operations via commands like php yii <command>.
a yii2 console application is a cli-based program that runs php scripts outside the web server, enabling background tasks, scheduled jobs, and maintenance operations via commands like `php yii
In Yii2, the console application is a specialized instance of yii\console\Application, which extends yii\base\Application with features tailored for command-line execution. Unlike web applications that respond to HTTP requests, console applications handle input from the terminal and output text-based results—making them ideal for automation, data migration, cron-triggered cleanup, or batch processing.
Key Characteristics
- Runs via PHP CLI (not Apache/Nginx)
- Bootstrapped using the yii executable script (typically located in your project root)
- Organized around reusable, self-contained commands, each mapped to a class extending yii\console\Controller
Basic Usage Example
From your project root, run:
php yii help
This lists all available commands. To execute a built-in command:
php yii migrate/up --interactive=0
This applies pending database migrations non-interactively.
Creating a Custom Command
Create commands/HelloController.php:
<?php
namespace app\commands;
use yii\console\Controller;
class HelloController extends Controller
{
public function actionIndex($name = 'World')
{
echo "Hello, $name!\n";
}
}Then run it:
php yii hello/index --name="Yii2" // Output: Hello, Yii2!
Common Use Cases
- Running database migrations (yii migrate)
- Generating code scaffolding (yii g/model User)
- Sending bulk emails or notifications
- Importing/exporting large datasets
- Scheduled cleanup (e.g., log rotation via cron)
Important Notes
✅ Console apps share the same configuration structure as web apps (e.g., console/config/main.php), but use separate config files and environments.
⚠️ Never expose console scripts via web access—ensure console/ is outside the document root and yii has proper file permissions.
⏱️ For recurring tasks, integrate with system cron or process managers (e.g., * * * * * cd /var/www/myapp && php yii hello/index >> /dev/null 2>&1).
By leveraging Yii2’s console application, developers gain a robust, framework-integrated way to manage operational tasks—securely, consistently, and maintainably.


















