yii 连接 mysql_mysql-动态更改数据库连接Yii

我正在一个项目中,一个Yii安装将运行多个网站.每个网站都有自己的数据库,因此数据库连接必须是动态的.

我做了什么,我创建了一个BeginRequestBehavior,它将在onBeginRequest中启动.在这里,我将检查已调用了哪个url,并确定匹配的数据库(不在我的代码中)并创建(或覆盖)“ db”组件.

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组件置于属性中.他们为什么这样做?恐怕这种方式将数据库连接建立的次数过多.

解决方法:

我使用模型函数定义她的数据库连接:

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',

),

来源:https://www.icode9.com/content-2-535151.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值