我正在從一個Yii安裝中運行多個網站的項目。每個網站都有自己的數據庫,所以數據庫連接必須是動態的。動態更改數據庫連接Yii
我做了什麼,我創建了一個BeginRequestBehavior,它將啓動'onBeginRequest'。在這裏,我將檢查哪個URL已被調用,並確定匹配的數據庫(不在我的代碼中)並創建(或覆蓋)'db'組件。
<?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);
}
}
它工作正常,但這是正確的方法?在其他方法中,我看到人們爲他們的模型創建自己的'MyActiveRecord'(擴展CActiveRecord)並將db組件放入屬性中。他們爲什麼這樣做?恐怕數據庫連接會以這種方式超出必要的次數。
我不需要多個數據庫,只有一個,它的變化取決於在你的網址上。你把db組件放在$ conection屬性中的原因是什麼? – davey