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

 

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

 

解决方法

 

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

 

1. class JUnicomActiveRecord extends Ar   
2. {
3. public $dbname = 'unicom1';
4. public $userIdKey = 'user_id';
5. protected $_userId;
6.
7. /**
8. * 获得DBConnenction(non-PHPdoc)
9. * @see CActiveRecord::getDbConnection()
10. */
11. public function getDbConnection()
12. {
13. if ($this->hasProperty($this->userIdKey))
14. {
15. $this->dbname = $this->chooseDb($this->{$this->userIdKey});
16. }
17. elseif ($this->_userId)
18. {
19. $this->dbname = $this->chooseDb($this->_userId);
20. }
21. return parent::getDbConnection();
22. }
23.
24. /**
25. * 选择数据库
26. */
27. public function chooseDb($userId)
28. {
29. $unicom = 'unicom2';
30. $userId = (float)$userId;
31. switch ($userId)
32. {
33. case $userId >= 10000 && $userId <= 29999999:
34. $unicom = 'unicom1';
35. break;
36. case $userId >= 30000000 && $userId <= 39999999:
37. $unicom = 'unicom2';
38. break;
39. case $userId >= 40000000 && $userId <= 49999999:
40. $unicom = 'unicom3';
41. break;
42. case $userId >= 50000000 && $userId <= 59999999:
43. $unicom = 'unicom4';
44. break;
45. case $userId >= 60000000 && $userId <= 69999999:
46. $unicom = 'unicom5';
47. break;
48. case $userId >= 70000000 && $userId <= 89999999:
49. $unicom = 'unicom6';
50. break;
51. case $userId >= 210000000 && $userId <= 239999999:
52. $unicom = 'unicom7';
53. break;
54. case $userId >= 240000000 && $userId <= 269999999:
55. $unicom = 'unicom8';
56. break;
57. case $userId >= 270000000 && $userId <= 299999999:
58. $unicom = 'unicom27';
59. break;
60. case $userId >= 1000000000 && ($userId % 2) == 0:
61. $unicom = 'unicom9';
62. break;
63. case $userId >= 1000000000 && ($userId % 2) == 1:
64. $unicom = 'unicom10';
65. break;
66. }
67. return $unicom;
68. }
69.
70. /**
71. * 设置用户ID
72. *
73. * @param int $user_id
74. */
75. public function setUserId($user_id)
76. {
77. $this->_userId = $user_id;
78. return $this;
79. }
80. }


2、配置数据库配置文件,将用户库中涉及到的数据库链接配置全部补全