我正在一個項目中,一個Yii安裝將運行多個網(wǎng)站.每個網(wǎng)站都有自己的數(shù)據(jù)庫,因此數(shù)據(jù)庫連接必須是動態(tài)的.
我做了什么,我創(chuàng)建了一個BeginRequestBehavior,它將在onBeginRequest中啟動.在這里,我將檢查已調(diào)用了哪個url,并確定匹配的數(shù)據(jù)庫(不在我的代碼中)并創(chuàng)建(或覆蓋)“ db”組件.
<?phpclass 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”(擴展CActiveRecord)并將db組件置于屬性中.他們?yōu)槭裁催@樣做?恐怕這種方式將數(shù)據(jù)庫連接建立的次數(shù)過多.
解決方法:
我使用模型函數(shù)定義她的數(shù)據(jù)庫連接:
public static $conection; // Model attributepublic 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',),
來源:https://www.icode9.com/content-2-535151.html