A simple class to use a different db for a module

You are viewing revision #2 of this wiki article.
This is the latest version of this article.
You may want to see the changes made in this revision.

« previous (#1)

  1. How to use
  2. Notes

What would you do if you want/need to have a different than the main database connection in an module's models?

How to use

Let's say we create a module with name test under the protected/modules/ folder.

Configuration

In your config file you can declare a module like:

'modules'=>array(••••••
    'test'=>array(
       'db'=>array(
           'class'=>'CDbConnection',
           'connectionString'=>'sqlite:'.dirname(__FILE__).'/../modules/bliig/data/blog.db',
       ),
   ),

Important: The 'class'=>'CDbConnection' is required, for this simple implementation.

CModule

In your TestModule.php file ( the class that extends the CModule ) under the protected/modules/test folder, declare a public property named db.

class TestModule extends CModule
{
  public $db;
  ...
}
Your models

Then you have to simple change the CActiveRecord class your module's models extends to EModuleActiveRecord

class EModuleActiveRecord extends CActiveRecord
{
    public function getDbConnection()
    {
        $db = Yii::app()->controller->module->db;
        return Yii::createComponent($db);
    }
}

Notes

In this scenario we had a module that we wanted to change database for, but the extension of the CActiveRecord and the override of the getDdConnection() is common general a common case. Make sure you import the EModuleActiveRecord. If you have generated the module with gii, just add file under the components or models folder.