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