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:
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.
The typical Yii2 application lifecycle follows these steps:
The lifecycle starts with the entry script located in the web/ directory:
index.php for web applicationsyii for console applicationsThe entry script sets up the application environment and loads the autoloader.
Basic Template Path:
web/index.phpAdvanced Template Path:
frontend/web/index.php
backend/web/index.phpConfiguration files are loaded based on the environment. The main configuration files are:
config/web.phpcommon/config/main.phpfrontend/config/main.phpbackend/config/main.phpYii2 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 sessionsThe urlManager component processes incoming URLs and maps them to the corresponding controller and action.
Example:
URL:
http://dynamicduniya.in/site/aboutRoute:
site/about → SiteController::actionAbout()The controller's action method executes the business logic.
Example:
public function actionAbout()
{
return $this->render('about');
}Action methods handle request data and process business logic before rendering views or sending JSON responses.
The controller renders views using the render() method.
Example:
return $this->render('index', ['name' => 'Dynamic Duniya']);Finally, Yii2 sends the generated output to the browser using the response component.
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();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 |
Yii2 allows you to customize the bootstrapping process by modifying the bootstrap() method of components or modules.
We can create a custom component that checks user authentication, dynamically registers modules, and sets custom application parameters.
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'
]
]
]);
}
}
}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',
],
],This approach helps in building scalable and modular applications.
After sending the response, Yii2 triggers the EVENT_AFTER_REQUEST event to clean up resources before shutting down.
| 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 |
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.
Sign in to join the discussion and post comments.
Sign in