I'm working on a project where multiple websites will be run from one Yii installation. Each website will have his own database though, so the database connection must be dynamically.
What i did, i created a BeginRequestBehavior which will be launched 'onBeginRequest'. Here i will check which url has been called and determine the matching database (not in my code yet) and create (or overwrite) the 'db' component.
<?php
class BeginRequestBehavior extends CBehavior
{
/**
* Attaches the behavior object to the component.
* @param CComponent the component that this behavior is to be attached to
* @return void
*/
public function attach($owner)
{
$owner->attachEventHandler('onBeginRequest', array($this, 'switchDatabase'));
}
/**
* Change database based on current url, each website has his own database.
* Config component 'db' is overwritten with this value
* @param $event event that is called
* @return void
*/
public function switchDatabase($event)
{
// Here some logic to check which url has been called..
$db = Yii::createComponent(array(
'class' => 'CDbConnection',
'connectionString' => 'mysql:host=localhost;dbname=test',
'emulatePrepare' => true,
'username' => 'secret',
'password' => 'verysecret',
'charset' => 'utf8',
'enableProfiling' => true,
'enableParamLogging' => true
));
Yii::app()->setComponent('db', $db);
}
}
It's working fine, but is this the correct approach? In other approaches i see people creating their own 'MyActiveRecord' (extending CActiveRecord) for their models and putting the db component in a property. Why do they do it? I'm afraid the database connection will be made too many times than necessary this way.