Components are the main building blocks of Yii applications. Is an instance of the yii\base\Component class or its subclasses. The three main functions used to distinguish it from other classes are:
Property (Recommended learning: yii framework)
Event (Event)
Behavior (Behavior)
Either used alone or in conjunction with each other. The application of these functions makes Yii classes more flexible and easier to use. Take the widget yii\jui\DatePicker as an example. This is a UI component that facilitates you to generate an interactive date picker in a view:
use yii\jui\DatePicker; echo DatePicker::widget([ 'language' => 'zh-CN', 'name' => 'country', 'clientOptions' => [ 'dateFormat' => 'yy-mm-dd', ], ]);use yii\jui\DatePicker; echo DatePicker::widget([ 'language' => 'zh-CN', 'name' => 'country', 'clientOptions' => [ 'dateFormat' => 'yy-mm-dd', ], ]);
This widget inherits from yii\base\Component, and its various Item properties can be easily overridden.
Precisely because of the powerful functions of components, they are slightly heavier than regular objects (Object) because they use additional memory and CPU time to process events and behaviors.
If you don’t need these two functions, you can inherit yii\base\Object instead of yii\base\Component. In this way, the component can be as efficient as a normal PHP object, while also supporting the property function.
When inheriting yii\base\Component or yii\base\Object, it is recommended that you use the following coding style:
If you need to override the constructor (Constructor ), pass in $config as the last parameter of the constructor method, and then pass it to the constructor of the parent class.
Always call the parent class's constructor at the end of your overridden constructor.
If you override the yii\base\BaseObject::init() method, please make sure you call the init method of the parent class at the beginning of the init method.
<?php namespace yii\components\MyClass; use yii\base\BaseObject; class MyClass extends BaseObject { public $prop1; public $prop2; public function __construct($param1, $param2, $config = []) { // ... 在应用配置之前初始化 parent::__construct($config); } public function init() { parent::init(); // ... 应用配置后进行初始化 } }
In addition, in order for the component to be correctly configured when creating an instance, please follow the following operation process:
$component = new MyClass(1, 2, ['prop1' => 3, 'prop2' => 4]); // 方法二: $component = \Yii::createObject([ 'class' => MyClass::className(), 'prop1' => 3, 'prop2' => 4, ], [1, 2])
The above is the detailed content of What are yii2.0 components?. For more information, please follow other related articles on the PHP Chinese website!