我正在从一个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