您的位置:首页 > 编程语言 > PHP开发

Yii框架分表设计

2011-12-15 18:22 155 查看
需求:原网站功能庞大,数据库服务器与数据库众多,有部分数据单表已经无法满足我们的需求。我们便有了分表的需求

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

解决方法:1、新建protected/sinashowExt/JActiveRecord.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、为了兼容以前的程序。我们重写protected/component/Ar.php文件来继承JActiveRecord类,代码如下:

class Ar extends JActiveRecord
{
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: