在实际工作中,有主从分离,随机读取从服务器等需求。我是这样来解决的。
class YLActiveRecord extends CActiveRecord{
public $YL_DBType='';
/*
* 重写CActiveRecord,中的方法,该方法取得main.php 中定义的数据库连接数组
*/
public function getDbConnection()
{
$this->YL_DBType;
switch ($this->YL_DBType)
{
case 'ylslave':
$yldb='dbread';
break;
case 'ylmaster':
$yldb='db';
break;
default:
$yldb='db';
}
/*
* 测试定义为随机链接
*/
$yldb=array('db','dbread');
$i=rand(0,1);
self::$db=Yii::app()->getComponent($yldb[$i]);
if(self::$db instanceof CDbConnection)
return self::$db;
else
throw new CDbException(Yii::t('yii','Active Record requires a "db" CDbConnection application component.'));
}
protected function beforeSave()
{
$this->YL_DBType='ylmaster';
parent::beforeSave();
}
protected function beforeDelete()
{
$this->YL_DBType='ylmaster';
parent::beforeDelete();
}
protected function beforeFind()
{
$this->YL_DBType='ylslave';
parent::beforeFind();
}
}
这里还可以对从服务器做随机选择(出错选择)等,各位如有需要可自行加入。在models继承此类即可。
重写了CActiveRecord中的beforeSave,beforeFind,getDbConnection等方法。经测试yii 1.1.8中可用。