Yii2 Configuration Basics

Introduction

Yii2 provides a flexible and structured configuration system that allows developers to manage application settings efficiently. Configuration files in Yii2 define database connections, components, modules, behaviors, and application-specific parameters. Understanding how configuration works is crucial for customizing and optimizing your Yii2 application.


1. Yii2 Configuration Files

Yii2 stores configuration settings in PHP array files, primarily located in the config/ directory. The key configuration files are:

For Basic Template:

  • config/web.php → Web application settings
  • config/console.php → Console application settings
  • config/db.php → Database configuration

For Advanced Template:

  • common/config/main.php → Common settings for frontend & backend
  • common/config/main-local.php → Local overrides (e.g., database credentials)
  • frontend/config/main.php → Frontend-specific settings
  • backend/config/main.php → Backend-specific settings
  • console/config/main.php → Console application settings

2. Setting Up Database Connection

Basic Template (config/db.php):

return [
    'class' => 'yii\db\Connection',
    'dsn' => 'mysql:host=localhost;dbname=dynamic_duniya',
    'username' => 'root',
    'password' => '',
    'charset' => 'utf8mb4',
];

Advanced Template (common/config/main-local.php):

return [
    'components' => [
        'db' => [
            'class' => 'yii\db\Connection',
            'dsn' => 'mysql:host=localhost;dbname=dynamic_duniya',
            'username' => 'root',
            'password' => '',
            'charset' => 'utf8mb4',
        ],
    ],
];

Note: Advanced Template uses main-local.php for local configurations.


3. Configuring Components

Yii2 allows configuring application components in the components section of the configuration file.

Example: Configuring the mailer component in web.php (Basic Template)

'components' => [
    'mailer' => [
        'class' => 'yii\swiftmailer\Mailer',
        'useFileTransport' => true, // Change to false to enable real email sending
    ],
],

4. Setting Application Parameters

Yii2 applications can have custom parameters defined in params.php.

Example (config/params.php in Basic Template)

return [
    'adminEmail' => 'admin@dynamicduniya.com',
    'siteName' => 'Dynamic Duniya',
];

To access parameters in the code:

Yii::$app->params['adminEmail'];

5. URL Management and Pretty URLs

By default, Yii2 uses query parameters in URLs, but we can enable pretty URLs using URL Manager.

Enable Pretty URLs (config/web.php)

'components' => [
    'urlManager' => [
        'enablePrettyUrl' => true,
        'showScriptName' => false,
        'rules' => [
            '<controller:\w+>/<action:\w+>' => '<controller>/<action>',
        ],
    ],
],

Now, instead of:

http://localhost/index.php?r=site/contact

You can use:

http://localhost/site/contact

6. Configuring Error Handling

Yii2 provides built-in error handling through the errorHandler component. By default, Yii2 already has an error action configured in SiteController.

Enable Error Page (config/web.php in Basic Template)

'components' => [
    'errorHandler' => [
        'errorAction' => 'site/error',
    ],
],

By default, Yii2 has an error.php view in views/site/error.php that displays error messages. If needed, you can customize this file for a better user experience.

Customize Error Page (config/web.php in Basic Template)

'components' => [
    'errorHandler' => [
        'errorAction' => 'site/error',
    ],
],

Create the error action in SiteController.php:

public function actionError()
{
    $exception = Yii::$app->errorHandler->exception;
    if ($exception !== null) {
        return $this->render('error', ['exception' => $exception]);
    }
}

7. Caching Configuration

Yii2 supports various caching mechanisms like file caching, database caching, and Redis/Memcached.

Example: Enable file caching (config/web.php):

'components' => [
    'cache' => [
        'class' => 'yii\caching\FileCache',
    ],
],

8. Configuring Session and Cookies

To configure session management, modify the session component:

'components' => [
    'session' => [
        'class' => 'yii\web\Session',
        'timeout' => 86400, // 1-day session timeout
    ],
],

To configure cookies:

'components' => [
    'response' => [
        'class' => 'yii\web\Response',
        'on beforeSend' => function ($event) {
            Yii::$app->response->cookies->add(new \yii\web\Cookie([
                'name' => 'test_cookie',
                'value' => 'DynamicDuniya',
                'expire' => time() + 3600, // 1 hour
            ]));
        },
    ],
],

Conclusion

Yii2’s configuration system is flexible and modular, allowing developers to customize every aspect of their application. In this tutorial, we covered database connections, components, URL management, caching, and error handling.

Next Tutorial:

In the next tutorial, we will explore Routing and Controllers in Yii2 to understand how requests are handled.