Connection.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. <?php
  2. /**
  3. * 数据库连接类
  4. *
  5. * @author Jinhui Zhu<jinhui.zhu@live.cn>2015-12-10 14:42
  6. */
  7. namespace Qii\Driver\Pdo;
  8. class Connection extends \Qii\Driver\ConnBase implements \Qii\Driver\ConnIntf
  9. {
  10. const VERSION = '1.2';
  11. /**
  12. * @var array $_dbInfo 数据库配置
  13. */
  14. protected $_dbInfo;
  15. /**
  16. * @var res $_instanceConnection 数据库连接
  17. */
  18. protected $_instanceConnection;
  19. public function __construct()
  20. {
  21. $this->_dbInfo = \Qii\Config\Register::getAppConfigure(\Qii\Config\Register::get(\Qii\Config\Consts::APP_DB));
  22. if(!isset($this->_dbInfo['use_db_driver'])) $this->_dbInfo['use_db_driver'] = 'mysql';
  23. }
  24. /**
  25. * 获取读数据的连接资源
  26. * @return res
  27. */
  28. public function getReadConnection()
  29. {
  30. $dbInfo = $this->_dbInfo['master'];
  31. $useSlave = false;
  32. if ($this->_dbInfo['readOrWriteSeparation'] && $this->_dbInfo['slave']) {
  33. $i = rand(0, count($this->_dbInfo['slave']) - 1);
  34. $dbInfo = $this->_dbInfo['slave'][$i];
  35. $useSlave = true;
  36. }
  37. if ($useSlave) {
  38. try {
  39. if ($this->_dbInfo['use_db_driver'] == 'mssql') {
  40. $dsn = 'odbc:Driver={SQL Server};Server=' . $dbInfo['host'] . ';Database=' . $dbInfo['db'] . ';';
  41. } else {
  42. $dsn = $this->_dbInfo['use_db_driver'] . ":host=" . $dbInfo['host'] . ";dbname=" . $dbInfo['db'];
  43. }
  44. return new \PDO($dsn, $dbInfo['user'], $dbInfo['password']);
  45. } catch (Exception $e) {
  46. return $this->getWriteConnection();
  47. }
  48. }
  49. return $this->getWriteConnection();
  50. }
  51. /**
  52. * 获取写数据的连接资源
  53. * @return res
  54. */
  55. public function getWriteConnection()
  56. {
  57. $dbInfo = $this->_dbInfo['master'];
  58. try {
  59. if ($this->_dbInfo['use_db_driver'] == 'mssql') {
  60. $dsn = 'odbc:Driver={SQL Server};Server=' . $dbInfo['host'] . ';Database=' . $dbInfo['db'] . ';';
  61. } else {
  62. $dsn = $this->_dbInfo['use_db_driver'] . ":host=" . $dbInfo['host'] . ";dbname=" . $dbInfo['db'];
  63. }
  64. return new \PDO($dsn, $dbInfo['user'], $dbInfo['password']);
  65. } catch (Exception $e) {
  66. throw new \Qii\Exceptions\Errors(\Qii::i(1500, $dbInfo['host'], $dbInfo['user'], $dbInfo['password'], $dbInfo['db'], iconv('GB2312', 'UTF-8', $e->getMessage())), __LINE__);
  67. }
  68. }
  69. }