Configuration is widely used to create new objects or initialize existing objects in Yii. The configuration usually contains the class name of the object being created and a set of attributes to be assigned to the object. Initial value, the attributes here are Yii2 attributes.
You can also bind event handlers to the object's events, or attach behaviors to the object. Thus, while defining the initial value of the object, the dynamic characteristics of the object's runtime are fully specified. (Recommended learning: yii framework)
The configuration in the following code is used to create and initialize a database connection:
$config = [ 'class' => 'yii\db\Connection', 'dsn' => 'mysql:host=127.0.0.1;dbname=demo', 'username' => 'root', 'password' => '', 'charset' => 'utf8', ]; $db = Yii::createObject($config);
Yii::createObject() is the most commonly used method in Yii2 to create objects, and its content is the object taken from the DI Container.
This method accepts a configuration array and creates an object based on the class name specified in the array. After the object is instantiated, the remaining parameters are used to initialize the object's properties, events and behaviors.
In Yii2.1, the key value used to represent the class name in the configuration array has been changed from class to __class, but the principle of configuration remains unchanged.
For an existing object, you can use the Yii::configure() method to initialize its properties according to the configuration, like this:
Yii::configure($object, $config);
Please note that if you configure an existing object, Then the configuration array should not contain a class element with the specified class name.
Configuration is a feature of Yii2
In programming, there is a very important concept called "deletion", that is, an object A can rely on another object B to To complete specific functions, a typical application is the strategy pattern.
To implement "delegation", there must be such a process: when object A is instantiated, another object B is injected; A holds object B; object A delegates object B to complete a specific function.
"Inject", "hold" and "delegate" are all high-frequency words in design patterns. Through these operations, the functions of a class can be extended.
The above is the detailed content of How to configure yii2. For more information, please follow other related articles on the PHP Chinese website!