Difference between #1 and #2 of A simple class to use a different db for a module

unchanged
Title
A simple class to use a different db for a module
unchanged
Category
Tips
unchanged
Tags
module, database, active record, tips
changed
Content
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
<code>protected/modules/</code> folder.

###Configuration
In your config file you can declare a module like:

~~~
[php]

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

__Important:__ The <code>'class'=>'CDbConnection'</code> is
required, for this simple implementation.

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

~~~
[php]
class TestModule extends CModule
{
  public function $db;
  ...
}
~~~

###Your models
Then you have to simple change the <code>CActiveRecord</code> class
your module's models extends to
[<code>EModuleActiveRecord</code>](http://dmtrs.devio.us/EModuleActiveRecord.tar.gz)

~~~
[php]
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 <code>CActiveRecord</code> and the 
override of the <code>getDdConnection()</code> is common general a
common case.
Make sure you import the <code>EModuleActiveRecord</code>. If you
have generated the module with gii, just add file under the
components or models folder.