Dealing with components in Yii application

In this tutorial you will learn how  to deal with compoments in yii application , Let’s take a look at the application initialization happening in the index.php entry point file:

require(__DIR__ . '/../vendor/yiisoft/yii2/Yii.php');
$config = require(__DIR__ . '/../config/web.php');
(new yii\web\Application($config))->run();

As per the ideology of Yii, the preceding three lines mean the following:

  1. Set up the Yii class definition.
  2. Create the yii\web\Application instance.
  3. Create various components declared in the components section of $config and attach them to the application instance.
  4. Next, perform all the other processing of $config like setting up the application’s own attributes.
  5. Attach the loaded yii\web\Application instance to the Yii class as the Yii::$app static variable.

In step 3, the components are created using the following rule: each array inside the components section of the application config is transformed into the instance of the class mentioned in the class key of the array, and other key/value pairs define the initial values that should be set for the properties of these instances. This rule is recursive. There are some special components for which the application knows the default classes beforehand. These components will be attached to the application as properties whose names are equal to the key/value pairs of the configuration in the components section.

For example, consider the following configuration snippet from the components section, perfectly fitting our didactic purposes:

        'log' => [
            'traceLevel' => 3,
            'targets' => [
                [
                    'class' => 'yii\log\FileTarget',
                    'levels' => ['error', 'warning'],
                ],
            ],
        ],

This configuration means that the following code will be executed during the creation of the application:

$log = new yii\log\Logger; // default class name
$log->traceLevel = 3;
$fileTarget = new yii\log\FileTarget;
$fileTarget->levels = ['error', 'warning'];
$log->targets = [$fileTarget];
Yii::$app->log = $log;

There is a whole bunch of components that are attached by default to any application. Their IDs, by which they are mentioned in the configuration, are already known, so Yii 2 knows which classes to use for these components even if you don’t specify them.

Also, basically, each array that has a key named class and a valid class name as the value of this key will be treated as the configuration for the instance of that class.

Tip

These rules are encapsulated in the Yii::createObject() invocation. You can always consult the source code for an enthralling adventure into the Dependency Injection Containers implementation, which we will skip in this book both because these implementation details are irrelevant to us and to save our sanity overall.

As soon as the log component is generated, it is attached to the application as the log property. As a result, you’ll be able to reach this newly created instance of the yii\log\Logger component with the following incantation:

Yii::$app->log

The logger is not so useful in this case though as it is usually used only indirectly through the Yii::error(), Yii::warning(), Yii::info(), and Yii::trace() calls (you probably already know what they do).

Here is a list of the components attached to both yii\console\Application and yii\web\Application by default, whether you specify the configuration for them or not:

Component IDComponent class
logyii\log\Dispatcher
formatteryii\base\Formatter
i18nyii\i18n\I18N
maileryii\swiftmailer\Mailer
urlManageryii\web\UrlManager
viewyii\web\View
assetManageryii\web\AssetManager
securityyii\base\Security

The following components are attached only to the console application:

Component IDComponent class
requestyii\console\Request
responseyii\console\Response
errorHandlerYii\console\ErrorHandler

The following components are attached only to the web application:

Component IDComponent class
requestyii\web\Request
responseyii\web\Response
sessionyii\web\Session
useryii\web\User
errorHandleryii\web\ErrorHandler

Note that both the console and web applications have the response, request, and errorHandler components, but they are of different classes.

In case Yii 2 updates itself in some way or another, you can always see the actual list of the built-in components inside the definition of the Application.coreComponents() method.

The most important point of this system of components is that nothing prevents you from creating and registering your own component. It is indistinguishable from the built-in components.

About the author

Deven Rathore

Deven Rathore

I'm Deven Rathore, a multidisciplinary & self-taught designer with 3 years of experience. I'm passionate about technology, music, coffee, traveling and everything visually stimulating. Constantly learning and experiencing new things.

Pin It on Pinterest

Shares