官术网_书友最值得收藏!

  • Mastering Yii
  • Charles R. Portwood II
  • 393字
  • 2021-07-23 14:30:30

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.

主站蜘蛛池模板: 沙雅县| 萨迦县| 新巴尔虎左旗| 和平县| 荣昌县| 平江县| 永修县| 阆中市| 合作市| 秭归县| 勐海县| 山丹县| 安乡县| 祁连县| 尼木县| 怀仁县| 祁门县| 海城市| 石屏县| 海宁市| 密山市| 色达县| 枣强县| 永安市| 武冈市| 洛隆县| 石河子市| 神池县| 浙江省| 富阳市| 怀仁县| 教育| 九龙城区| 六盘水市| 全南县| 修文县| 揭阳市| 靖西县| 开原市| 息烽县| 张家港市|