Yii框架分库设计

需求:原网站功能庞大,数据库服务器与数据库众多,有部分数据单库多表都不足以应付业务的快速增长(例如用户系统)。我们便有了分库的需求

 

问题:YII单DB方式已经满足不了我们的需求,急切需要对YII进行扩展设计,支持数据库分库设计

 

解决方法


1、在protected/component目录下面新建一个JUnicomActiveRecord.php文件。代码如下:

class JUnicomActiveRecord extends Ar 
{
	public $dbname		= 'unicom1';
	public $userIdKey	= 'user_id';
	protected $_userId;
	
	/**
	 * 获得DBConnenction(non-PHPdoc)
	 * @see CActiveRecord::getDbConnection()
	 */
	public function getDbConnection()
	{
		if ($this->hasProperty($this->userIdKey))
		{
			$this->dbname	= $this->chooseDb($this->{$this->userIdKey});
		}
		elseif ($this->_userId) 
		{
			$this->dbname	= $this->chooseDb($this->_userId);
		}
		return parent::getDbConnection();
	}
	
	/**
     * 选择数据库
     */
    public function chooseDb($userId)
    {
        $unicom = 'unicom2';
        $userId = (float)$userId;
    	switch ($userId)
    	{
    		case $userId >= 10000 && $userId <= 29999999:
    			$unicom = 'unicom1';
    			break;
    		case $userId >= 30000000 && $userId <= 39999999:
    			$unicom = 'unicom2';
    			break;
    		case $userId >= 40000000 && $userId <= 49999999:
    			$unicom = 'unicom3';
    			break;
    		case $userId >= 50000000 && $userId <= 59999999:
    			$unicom = 'unicom4';
    			break;
    		case $userId >= 60000000 && $userId <= 69999999:
    			$unicom = 'unicom5';
    			break;
    		case $userId >= 70000000 && $userId <= 89999999:
    			$unicom = 'unicom6';
    			break;
    		case $userId >= 210000000 && $userId <= 239999999:
    			$unicom = 'unicom7';
    			break;
    		case $userId >= 240000000 && $userId <= 269999999:
    			$unicom = 'unicom8';
    			break;
    		case $userId >= 270000000 && $userId <= 299999999:
    			$unicom = 'unicom27';
    			break;
    		case $userId >= 1000000000 && ($userId % 2) == 0:
    			$unicom = 'unicom9';
    			break;
    		case $userId >= 1000000000 && ($userId % 2) == 1:
    			$unicom = 'unicom10';
    			break;
         }
         return $unicom;
    }
    
    /**
     * 设置用户ID
     *
     * @param int $user_id
     */
    public function setUserId($user_id)
    {
    	$this->_userId	= $user_id;
    	return $this;
    }
}
2、配置数据库配置文件,将用户库中涉及到的数据库链接配置全部补全

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值