BaseModuleAR class with MultiActiveRecord

You are viewing revision #1 of this wiki article.
This version may not be up to date with the latest version.
You may want to view the differences to the latest version.

next (#2) »

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:

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.

'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',