Connection.php 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. <?php
  2. namespace Qii\Driver\Mysqli;
  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 = mysqli_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", mysqli_connect_error())), true);
  27. mysqli_select_db($connection, $dbInfo['db']);
  28. return $connection;
  29. } catch (Exception $e) {
  30. return $this->getWriteConnection();
  31. }
  32. }
  33. return $this->getWriteConnection();
  34. }
  35. /**
  36. * 获取写数据的连接资源
  37. *
  38. */
  39. public function getWriteConnection()
  40. {
  41. $dbInfo = $this->_dbInfo['master'];
  42. try {
  43. $connection = @mysqli_connect($dbInfo['host'], $dbInfo['user'], $dbInfo['password'], $dbInfo['db']);
  44. if (!$connection) throw new \Qii\Exceptions\Errors(\Qii::i(1501, iconv("GBK", "UTF-8//TRANSLIT", mysqli_connect_error())), true);
  45. mysqli_select_db($connection, $dbInfo['db']);
  46. return $connection;
  47. } catch (Exception $e) {
  48. throw new \Qii\Exceptions\Errors(\Qii::i(1500, $dbInfo['host'], $dbInfo['user'], $dbInfo['password'], $dbInfo['db'], $e->getMessage()), __LINE__);
  49. }
  50. }
  51. }