gpt4 book ai didi

mysql - 动态更改数据库连接 Yii

转载 作者:可可西里 更新时间:2023-11-01 08:06:03 26 4
gpt4 key购买 nike

我正在从事一个项目,其中多个网站将从一个 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)并将数据库组件放入属性中。他们为什么这样做?恐怕数据库连接会以这种方式建立太多次。

最佳答案

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

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."));
}
}

ma​​in.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',
),

关于mysql - 动态更改数据库连接 Yii,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19771348/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com