Difference between #1 and #2 of BaseModuleAR class with MultiActiveRecord

unchanged
Title
BaseModuleAR class with MultiActiveRecord
unchanged
Category
Tips
unchanged
Tags
multiactiverecord, ajax request multiply, active record, module
changed
Content
[MultiActiveRecord](http://www.yiiframework.com/extension/multiactiverecord/
"MultiActiveRecord")MultiActiveRecord
[http://www.yiiframework.com/extension/multiactiverecord/] is an extension
that add support for multiple database connection for your application.

Imagine that you have to dev for several projects at once. You want to share the
same repo of extensions and components, but do not want to copy them over and
over between project.

Fortunately, you can using Gii to create a module layout, set up a
ModuleBaseActiveRecord class, and using it as a base class for your module
models.

In this class, you can simply tell Yii to use another DB connection, to develope
your feature in another DB.

Here is the code I use:



~~~
[php]
abstract class ModuleBaseActiveRecord extends MultiActiveRecord {
	public function connectionId(){
		if (! empty(Yii::app()->controller->module->id)){
			$moduledb = ((string) Yii::app()->controller->module->id) . 'db';
			if (is_object(Yii::app()->$moduledb) && (Yii::app()->$moduledb
instanceof CDbConnection))
			return $moduledb;
		}
         return 'db';
   }

~~~

And then in your configuration file, specify the modules and the db connection
for this module. The above code tell Yii to search for a component named
[module-id]db.

~~~
[php]
'modules' => array('core', 'mod1', 'mod2'),
'components' => array(
   'db' => array( // Here go the main database, use for core module 
   ...
   ),
   'mod1db' => array ( // The database tables needed for mod1 module to work.
      'class' => 'CDbConnection',
   ...
   ),
   'mod2db' => array( // Another database for mod2
      'class' => 'CDbConnection',
      ...
   )
~~~