Yii框架数据库分库设计

阅读更多

现在项目中多数会用到数据库多库的切换场景,在Yii中是如何实践的呢?

其实通过动态设置

Yii::app()->setComponent(array('key'=>数据库连接的配置文件)); 

 具体代码:

hasComponent($dbLink)) {			
            return Yii::app()->$dbLink;
		}
		$dbConf = self::_getCityDBConfig($cityCode);
		if(FALSE === $dbConf) {           
            throw new CException("Did not declare the database configuration!");
        }       
        Yii::app()->setComponents(array($dbLink => $dbConf));  
		return Yii::app()->$dbLink;		
	}
	
	/**
	 * 获取城市DB配置。
	 *
	 * @param string $cityCode 城市简拼
	 * @return boolean|array DB配置或假
	 */
	private static function _getCityDBConfig($cityCode){
		$cityCode = strtoupper($cityCode);
		$dbconfig = self::_getMasterConf($cityCode);
		if($slave){
			$dbconfig['slaves'] = self::_getSlaveConf($cityCode);
		}
		return $dbconfig;
	}	
    
   
	
	/**
	 * 取主库配置文件。
	 *
	 * @param string $cityCode
	 * @return array
	 */
	private static function _getMasterConf($cityCode) {
		return array(
            'class' => 'DbConnection',
            'connectionString' => mysql:host=;dbname=;port=",
            'emulatePrepare' => true,
            'username' => ,
            'password' => ,
            'tablePrefix' => 't_',
            'charset' => 'utf8',
            'enableProfiling' => true, //
            'enableParamLogging' => true, //
        );
	}
	
	/**
	 * 取从库配置文件。
	 *
	 * @param string $cityCode
	 * @return array
	 */
	private static function _getSlaveConf($cityCode) {
		return array(
                array(
                    'connectionString' => mysql:host=;dbname=;port=",
                    'emulatePrepare' => true,
                    'username' => ,
                    'password' => ,
                    'charset' => 'UTF8',
                    'tablePrefix' => 't',
                    'enableParamLogging' => YII_DEBUG,
                    'schemaCacheID' => 'cache',
                    'schemaCachingDuration' => 0,
                )
            );
	}
}

 调用方法:

 

createCommand("select 8 * 8;")->queryAll();
?>

 

你可能感兴趣的:(php,mysql,Yi)