- Yii2 Framework
-
Introduction & Setup
- Introduction to Yii2 Framework
- Installing Yii2 (Basic & Advanced Templates)
- Understanding Yii2 Directory Structure
- Yii2 Configuration Basics
- Routing & Pretty URLs in Yii2
-
Yii2 Core Concepts
- Yii2 Application Bootstrapping & Lifecycle
- Understanding Yii2 Request & Response Handling
- Working with Yii2 Components & Helpers
- Yii2 Widgets & Using Built-in Widgets
- Yii2 Helpers & Utility Classes
-
Models & Database Operations
- Yii2 Models, Active Record & Database Connections
- CRUD Operations in Yii2
- Yii2 Query Builder & DAO (Direct SQL Queries)
- Handling Relationships in Yii2 Active Record
- Yii2 Migrations & Seeding
-
Views, Layouts & Themes
- Yii2 Views & Layouts
- Yii2 Asset Bundles & Asset Management
- Integrating Bootstrap in Yii2
- Yii2 Theme Integration
- Yii2 Custom Widgets & Reusable Components
-
Forms, Validation & Data Presentation
- Yii2 Forms & Validation
- Using Yii2 GridView & ListView Widgets
- Yii2 Pagination & Sorting
- Yii2 File Uploads
-
Security & User Management
- User Authentication in Yii2
- Role-Based Access Control (RBAC) in Yii2
- Yii2 Security Features
-
Console Commands & Advanced Features
- Yii2 Console Commands
- Yii2 Events & Behaviors
- Yii2 RESTful API Development
- Consuming Third-Party APIs in Yii2
- Yii2 Background Jobs & Queue System
-
Performance Optimization & Caching
- Yii2 Caching Techniques
- Yii2 Performance Optimization
- Debugging & Logging in Yii2
-
Deployment & Best Practices
- Deploying Yii2 Applications
- Yii2 Best Practices & Large-Scale Application Structure
- Yii2 Multilingual & Localization Support
- Yii2 Module Development
- Integrating Yii2 with Frontend Frameworks (Angular/Vue/React)
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.
Prepare for Interview
- Debugging in Python
- Multithreading and Multiprocessing in Python
- Context Managers in Python
- Decorators in Python
- Generators in Python
- Requests in Python
- Django
- Flask
- Matplotlib/Seaborn
- Pandas
- NumPy
- Modules and Packages in Python
- File Handling in Python
- Error Handling and Exceptions in Python
- Indexing and Performance Optimization in SQL
Random Blogs
- Quantum AI – The Future of AI Powered by Quantum Computing
- Datasets for Speech Recognition Analysis
- Downlaod Youtube Video in Any Format Using Python Pytube Library
- Career Guide: Natural Language Processing (NLP)
- The Ultimate Guide to Starting a Career in Computer Vision
- Loan Default Prediction Project Using Machine Learning
- Store Data Into CSV File Using Python Tkinter GUI Library
- Datasets for analyze in Tableau
- Robotics & AI – How AI is Powering Modern Robotics
- Python Challenging Programming Exercises Part 3
- Big Data: The Future of Data-Driven Decision Making
- AI & Space Exploration – AI’s Role in Deep Space Missions and Planetary Research
- Understanding AI, ML, Data Science, and More: A Beginner's Guide to Choosing Your Career Path
- Why to learn Digital Marketing?
- Mastering SQL in 2025: A Complete Roadmap for Beginners
Datasets for Machine Learning
- Ozone Level Detection Dataset
- Bank Transaction Fraud Detection
- YouTube Trending Video Dataset (updated daily)
- Covid-19 Case Surveillance Public Use Dataset
- US Election 2020
- Forest Fires Dataset
- Mobile Robots Dataset
- Safety Helmet Detection
- All Space Missions from 1957
- OSIC Pulmonary Fibrosis Progression Dataset
- Wine Quality Dataset
- Google Audio Dataset
- Iris flower dataset
- Artificial Characters Dataset
- Bitcoin Heist Ransomware Address Dataset