BaseModuleAR class with MultiActiveRecord

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',
      ...
   )
2 0
0 follower
Viewed: 11 491 times
Version: 1.1
Category: Tips
Written by: dinhtrung
Last updated by: Gustavo
Created on: Jun 16, 2011
Last updated: 8 years ago
Update Article

Revisions

View all history

Related Articles