ConnBase.php 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. <?php
  2. namespace Qii\Driver;
  3. /**
  4. * 数据库连接基类
  5. *
  6. * @author Jinhui Zhu<jinhui.zhu@live.cn> 2015-12-10 14:34
  7. */
  8. class ConnBase
  9. {
  10. const VERSION = '1.2';
  11. /**
  12. * @var $allowExec 读写对应的数据库配置文件
  13. */
  14. public $allowExec = array("WRITE" => 'master', 'READ' => 'slave');
  15. /**
  16. * 获取数据库配置中指定的key的值,不指定则获取全部
  17. * @param string key 数据库配置中指定的key
  18. */
  19. public function getDBInfo($key = null)
  20. {
  21. if ($key != null) return isset($this->_dbInfo[$key]) ? $this->_dbInfo[$key] : false;
  22. return $this->_dbInfo;
  23. }
  24. /**
  25. * 通过sql语句判断是读还是写操作
  26. * @param $sql 读/写的sql语句
  27. */
  28. protected function prepare($sql)
  29. {
  30. $default = "READ";
  31. $readMode = "/^SELECT\s/u";
  32. $writeMode = "/^(UPDATE)|(REPLACE)|(DELETE)\s/u";
  33. $isRead = preg_match($readMode, $sql);
  34. $isWrite = preg_match($writeMode, $sql);
  35. if ($isWrite) $default = "WRITE";
  36. if (!isset($this->allowExec[$default])) $default = 'WRITE';
  37. return $default;
  38. }
  39. /**
  40. * 通过sql获取连接资源
  41. *
  42. * @param String $sql 通过sql语句获取读/写操作对应的res
  43. * @return res
  44. */
  45. public function getConnectionBySQL($sql)
  46. {
  47. $default = $this->prepare($sql);
  48. if (isset($this->_connections[$default])) return $this->_connections[$default];
  49. switch ($default) {
  50. case 'READ':
  51. return $this->_connections[$default] = $this->getReadConnection();
  52. break;
  53. default:
  54. return $this->_connections['WRITE'] = $this->getWriteConnection();
  55. break;
  56. }
  57. throw new \Exception('Call undefined driver', __LINE__);
  58. }
  59. }