Components and objects
There are two base classes that almost everything in Yii2 extends from: the Component
class and the Object
class.
Components
In Yii2, the Component
class has replaced the CComponent
class from Yii1. In Yii1, components act as service locators that host a specific set of application components that provide different services for the processing of requests. Each component in Yii2 can be accessed using the following syntax:
Yii::$app->componentID
For example, the database component can be accessed using this:
Yii::$app->db
The cache component can be accessed using this:
Yii::$app->cache
Yii2 automatically registers each component at runtime via the application configuration that we mentioned in the previous section by name.
To improve performance in Yii2 applications, components are lazy-loaded or only instantiated the first time they are accessed. This means that if the cache component is never used in your application code, the cache component will never be loaded. At times, however, this can be nonideal, so to force load a component, you can bootstrap it by adding it to the bootstrap configuration option in either config/web.php
or config/console.php
. For instance, if we want to bootstrap the log component, we can do that as follows:
<?php return [ 'bootstrap' => [ 'log' ], […] ]
The bootstrap
option behaves in a manner similar to the preload option in Yii1—any component that you want or need to be instantiated on bootstrap will be loaded if it is in the bootstrap
section of your configuration file.
Note
For more information on service locators and components, ensure that you read the Definitive Guide to Yii guide located at http://www.yiiframework.com/doc-2.0/guide-concept-service-locator.html and http://www.yiiframework.com/doc-2.0/guide-structure-application-components.html.
Objects
In Yii2, almost every class that doesn't extend from the Component
class extends from the Object
class. The Object
class is the base class that implements the property feature. In Yii2, the property feature allows you to access a lot of information about an object, such as the __get
and __set
magic methods, as well as other utility functions, such as hasProperty()
, canGetProperty()
, and canSetProperty()
. Combined, this makes objects in Yii2 extremely powerful.
Tip
The object
class is extremely powerful, and many classes in Yii extend from it. Despite this, using the magic methods __get
and __set
yourself is not considered best practice as it is slower than a native PHP method and doesn't integrate well with your IDE's autocomplete tool and documentation tools.