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:

  1. What is Bootstrapping in Yii2?
  2. Yii2 Application Lifecycle Overview
  3. Step-by-Step Request Flow
  4. Yii2 Entry Scripts
  5. Application Components Initialization
  6. Customizing the Bootstrapping Process (Advanced Usage)
  7. Application Shutdown
  8. 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:

  1. Entry Script Execution
  2. Configuration Loading
  3. Application Initialization
  4. Request Routing
  5. Controller Execution
  6. Action Execution
  7. View Rendering
  8. 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 applications
  • yii 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 connection
  • urlManager → Routing
  • request → Handling incoming requests
  • session → 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:

ComponentPurposeConfiguration File
dbDatabase connectionconfig/db.php
urlManagerRoutingconfig/web.php
sessionSession managementconfig/web.php
cacheCachingconfig/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

StepDescription
Entry ScriptInitializes the application
ConfigurationLoads settings from files
Component InitializationRegisters components
Request HandlingProcesses user requests
Action ExecutionCalls controller action
Response GenerationSends the response back to the user
Application ShutdownCleans 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.