Connection.php 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. <?php
  2. namespace Qii\Driver\mysql;
  3. class Connection extends \Qii\Driver\ConnBase implements \Qii\Driver\ConnIntf
  4. {
  5. const VERSION = '1.2';
  6. protected $_dbInfo;
  7. public function __construct()
  8. {
  9. $this->_dbInfo = \Qii\Config\Register::getAppConfigure(\Qii\Config\Register::get(\Qii\Config\Consts::APP_DB));
  10. }
  11. /**
  12. * 获取读数据的连接资源
  13. */
  14. public function getReadConnection()
  15. {
  16. $dbInfo = $this->_dbInfo['master'];
  17. $useSlave = false;
  18. if ($this->_dbInfo['readOrWriteSeparation'] && $this->_dbInfo['slave']) {
  19. $i = rand(0, count($this->_dbInfo['slave']) - 1);
  20. $dbInfo = $this->_dbInfo['slave'][$i];
  21. $useSlave = true;
  22. }
  23. if ($useSlave) {
  24. try {
  25. $connection = mysql_connect($dbInfo['host'], $dbInfo['user'], $dbInfo['password'], $dbInfo['db']);
  26. if (!$connection) throw new \Qii\Exceptions\Errors(\Qii::i(1501, iconv("GBK", "UTF-8//TRANSLIT", mysql_error())), true);
  27. return $connection;
  28. } catch (Exception $e) {
  29. return $this->getWriteConnection();
  30. }
  31. }
  32. return $this->getWriteConnection();
  33. }
  34. /**
  35. * 获取写数据的连接资源
  36. *
  37. */
  38. public function getWriteConnection()
  39. {
  40. try {
  41. $connection = mysql_connect($dbInfo['host'], $dbInfo['user'], $dbInfo['password'], $dbInfo['db']);
  42. if (!$connection) throw new \Qii\Exceptions\Errors(\Qii::i(1501, iconv("GBK", "UTF-8//TRANSLIT", mysql_error())), true);
  43. return $connection;
  44. } catch (Exception $e) {
  45. throw new \Qii\Exceptions\Errors(\Qii::i(1500, $dbInfo['host'], $dbInfo['user'], $dbInfo['password'], $dbInfo['db'], $e->getMessage()));
  46. }
  47. }
  48. }