Tuesday, July 3, 2012

how components configuration works in YII

If you have worked with Yii before, then you have probably configured a database connection:
return array(

'components'=>array(
'db'=>array(
'class'=>'system.db.CDbConnection',
'connectionString'=>'mysql:host=localhost;dbname=database_
name',
'username'=>'root',
'password'=>'',
'charset'=>'utf8',
),

),

);
This way of configuring component is used when you want to use a component across all
application parts. With the preceding configuration, you can access a component by its name,
such as Yii::app()->db.
How it works…
When you are using the Yii::app()->db component for the first time directly or through
active record model, Yii creates a component and initializes its public properties with the
corresponding values provided in db array under the components section of the main.php
application configuration file. In the preceding code, 'connectionString' the value will
be assigned to CDbConnection::connectionString, 'username' will be assigned
to CDbConnection::username, and so on.
If you want to find out what 'charset' stands for or want to know what else you can
configure in the db component, then you need to know its class. In case of db component, the
class is CDbConnection. You can refer to its API page at http://www.yiiframework.
com/doc/api/CDbConnection/ and look for its public properties you can set from config.
In the preceding code, the 'class' property is a bit special because it is used to specify
component class name. It does not exist in the CDbConnection class. Therefore, it can be
used to override a class as follows:
return array(

'components'=>array(
'db'=>array(
'class'=>'application.components.MyDbConnection',

),

),

);
This way, you can override each application component and it is very useful whenever a
standard component does not fit your application.

No comments:

Post a Comment