- 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)
-
Special Topics
- Dependency Injection (DI) in Yii2
Yii2 Application Bootstrapping & Lifecycle
Introduction
Yii2 follows a structured bootstrapping and lifecycle process to handle every request efficiently. Understanding how Yii2 initializes and processes requests helps developers customize and optimize applications effectively.
In this tutorial, we will cover:
- What is Bootstrapping in Yii2?
- Yii2 Application Lifecycle Overview
- Step-by-Step Request Flow
- Yii2 Entry Scripts
- Application Components Initialization
- Customizing the Bootstrapping Process (Advanced Usage)
- Application Shutdown
- Best Practices
1. What is Bootstrapping in Yii2?
Bootstrapping is the process of initializing the core components of an application before processing user requests. Yii2 uses a predefined flow to load configurations, register components, and handle incoming requests.
2. Yii2 Application Lifecycle Overview
The typical Yii2 application lifecycle follows these steps:
- Entry Script Execution
- Configuration Loading
- Application Initialization
- Request Routing
- Controller Execution
- Action Execution
- View Rendering
- Response Sending
3. Step-by-Step Request Flow
Step 1: Entry Script Execution
The lifecycle starts with the entry script located in the web/
directory:
index.php
for web applicationsyii
for console applications
The entry script sets up the application environment and loads the autoloader.
Basic Template Path:
web/index.php
Advanced Template Path:
frontend/web/index.php
backend/web/index.php
Step 2: Configuration Loading
Configuration files are loaded based on the environment. The main configuration files are:
- Basic Template:
config/web.php
- Advanced Template:
common/config/main.php
frontend/config/main.php
backend/config/main.php
Step 3: Application Initialization
Yii2 creates an application instance using:
$config = require __DIR__ . '/../config/web.php';
(new yii\web\Application($config))->run();
This initializes components like:
db
→ Database connectionurlManager
→ Routingrequest
→ Handling incoming requestssession
→ Managing sessions
Step 4: Request Routing
The urlManager
component processes incoming URLs and maps them to the corresponding controller and action.
Example:
URL:
http://dynamicduniya.in/site/about
Route:
site/about → SiteController::actionAbout()
Step 5: Controller Execution
The controller's action method executes the business logic.
Example:
public function actionAbout()
{
return $this->render('about');
}
Step 6: Action Execution
Action methods handle request data and process business logic before rendering views or sending JSON responses.
Step 7: View Rendering
The controller renders views using the render()
method.
Example:
return $this->render('index', ['name' => 'Dynamic Duniya']);
Step 8: Response Sending
Finally, Yii2 sends the generated output to the browser using the response
component.
4. Yii2 Entry Scripts
Yii2 applications use entry scripts to initialize the application and handle user requests.
Basic Template Entry Script:
require __DIR__ . '/../vendor/autoload.php';
require __DIR__ . '/../vendor/yiisoft/yii2/Yii.php';
$config = require __DIR__ . '/../config/web.php';
(new yii\web\Application($config))->run();
5. Application Components Initialization
Yii2 automatically initializes core components like:
Component | Purpose | Configuration File |
---|---|---|
db | Database connection | config/db.php |
urlManager | Routing | config/web.php |
session | Session management | config/web.php |
cache | Caching | config/web.php |
6. Customizing the Bootstrapping Process (Advanced Usage)
Yii2 allows you to customize the bootstrapping process by modifying the bootstrap() method of components or modules.
Example: Custom Bootstrap Component
We can create a custom component that checks user authentication, dynamically registers modules, and sets custom application parameters.
Step 1: Creating a Bootstrap Component
Create a new class inside components/CustomBootstrap.php
:
namespace app\components;
use Yii;
use yii\base\BootstrapInterface;
use yii\base\Application;
class CustomBootstrap implements BootstrapInterface
{
/**
* Bootstrap method to be called during application bootstrap stage.
* @param Application $app the application currently running
*/
public function bootstrap($app)
{
if (isset(Yii::$app->user->identity)) {
$user = Yii::$app->user->identity;
// Logout if user is cascaded or blocked
if ($user->isCascade || $user->isBlocked) {
Yii::$app->user->logout();
}
// Check for password expiry
Yii::$app->passwordexpirycheck->check($user);
}
// Set copyright dynamically based on domain
if ($_SERVER['SERVER_NAME'] == app.dynamicduniya.in') {
Yii::$app->params['copyrightText'] = 'Copyright © ' . date('Y') . ' Dynamic Duniya. All Rights Reserved. Users are advised to read Terms and Conditions carefully.';
}
// Dynamically register modules from the database
if ($app instanceof \yii\web\Application) {
Yii::configure($app, [
'modules' => [
'blog' => [
'class' => 'app\modules\blog\Module'
]
]
]);
}
}
}
Step 2: Registering the Bootstrap Component in Configuration
Now, add this component to your Yii2 configuration file (config/web.php
in Basic Template or common/config/main.php
in Advanced Template):
'bootstrap' => ['log', 'app\components\CustomBootstrap'],
'components' => [
'passwordexpirycheck' => [
'class' => 'app\components\PasswordExpiryCheck',
],
],
What This Custom Bootstrap Component Does?
- Logs out cascaded or blocked users before they can access the system.
- Checks password expiration using a custom component.
- Dynamically sets application parameters based on the domain.
- Registers Yii2 modules dynamically from the database.
This approach helps in building scalable and modular applications.
7. Application Shutdown
After sending the response, Yii2 triggers the EVENT_AFTER_REQUEST
event to clean up resources before shutting down.
8. Best Practices
- Always register components in the configuration file.
- Use modules for large applications.
- Customize bootstrapping for advanced tasks like logging or caching.
- Keep configuration clean and organized.
Yii2 Lifecycle Summary
Step | Description |
---|---|
Entry Script | Initializes the application |
Configuration | Loads settings from files |
Component Initialization | Registers components |
Request Handling | Processes user requests |
Action Execution | Calls controller action |
Response Generation | Sends the response back to the user |
Application Shutdown | Cleans up resources |
Conclusion
Yii2's bootstrapping and lifecycle process ensures that applications are initialized, processed, and terminated in a structured way. By understanding this flow, developers can customize and optimize their applications.
In the next tutorial, we will cover Understanding Yii2 Request & Response Handling. explaining how requests are handled efficiently.
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
- Create Virtual Host for Nginx on Ubuntu (For Yii2 Basic & Advanced Templates)
- What Is SEO and Why Is It Important?
- Mastering Python in 2025: A Complete Roadmap for Beginners
- Best Platform to Learn Digital Marketing in Free
- Robotics & AI – How AI is Powering Modern Robotics
- Understanding OLTP vs OLAP Databases: How SQL Handles Query Optimization
- Generative AI - The Future of Artificial Intelligence
- Variable Assignment in Python
- Understanding HTAP Databases: Bridging Transactions and Analytics
- The Ultimate Guide to Artificial Intelligence (AI) for Beginners
- OLTP vs. OLAP Databases: Advanced Insights and Query Optimization Techniques
- Deep Learning (DL): The Core of Modern AI
- How AI is Making Humans Weaker – The Hidden Impact of Artificial Intelligence
- Important Mistakes to Avoid While Advertising on Facebook
- Grow your business with Facebook Marketing
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