我正在一個(gè)項(xiàng)目中,一個(gè)Yii安裝將運(yùn)行多個(gè)網(wǎng)站.每個(gè)網(wǎng)站都有自己的數(shù)據(jù)庫(kù),因此數(shù)據(jù)庫(kù)連接必須是動(dòng)態(tài)的.
我做了什么,我創(chuàng)建了一個(gè)BeginRequestBehavior,它將在onBeginRequest中啟動(dòng).在這里,我將檢查已調(diào)用了哪個(gè)url,并確定匹配的數(shù)據(jù)庫(kù)(不在我的代碼中)并創(chuàng)建(或覆蓋)“ 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);
}
}
一切正常,但這是正確的方法嗎,?在其他方法中,我看到人們?yōu)樗麄兊哪P蛣?chuàng)建自己的“ MyActiveRecord”(擴(kuò)展CActiveRecord)并將db組件置于屬性中.他們?yōu)槭裁催@樣做?恐怕這種方式將數(shù)據(jù)庫(kù)連接建立的次數(shù)過(guò)多. 解決方法: 我使用模型函數(shù)定義她的數(shù)據(jù)庫(kù)連接:
public static $conection; // Model attribute
public function getDbConnection(){
if(self::$conection!==null)
return self::$conection;
else{
self::$conection = Yii::app()->db2; // main.php - DB config name
if(self::$conection instanceof CDbConnection){
self::$conection->setActive(true);
return self::$conection;
}
else
throw new CDbException(Yii::t('yii',"Active Record requires a '$conection' CDbConnection application component."));
}
}
main.php:
'db'=>array(
'connectionString' => 'mysql:host=192.168.1.*;dbname=database1',
'emulatePrepare' => true,
'username' => 'root',
'password' => 'password',
'charset' => 'utf8',
'enableProfiling'=>true,
'enableParamLogging' => true,
),
'db2'=>array(
'class'=>'CDbConnection',
'connectionString' => 'mysql:host=192.168.1.*;dbname=database2',
'emulatePrepare' => true,
'username' => 'root',
'password' => 'password',
'charset' => 'utf8',
),
來(lái)源:https://www./content-2-535151.html
|