Db.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. <?php
  2. /**
  3. * This file is part of workerman.
  4. *
  5. * Licensed under The MIT License
  6. * For full copyright and license information, please see the MIT-LICENSE.txt
  7. * Redistributions of files must retain the above copyright notice.
  8. *
  9. * @author walkor<walkor@workerman.net>
  10. * @copyright walkor<walkor@workerman.net>
  11. * @link http://www.workerman.net/
  12. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  13. */
  14. namespace GatewayWorker\Lib;
  15. use Config\Db as DbConfig;
  16. use Exception;
  17. /**
  18. * 数据库类
  19. */
  20. class Db
  21. {
  22. /**
  23. * 实例数组
  24. *
  25. * @var array
  26. */
  27. protected static $instance = array();
  28. /**
  29. * 获取实例
  30. *
  31. * @param string $config_name
  32. * @return DbConnection
  33. * @throws Exception
  34. */
  35. public static function instance($config_name)
  36. {
  37. if (!isset(DbConfig::$$config_name)) {
  38. echo "\\Config\\Db::$config_name not set\n";
  39. throw new Exception("\\Config\\Db::$config_name not set\n");
  40. }
  41. if (empty(self::$instance[$config_name])) {
  42. $config = DbConfig::$$config_name;
  43. self::$instance[$config_name] = new DbConnection($config['host'], $config['port'],
  44. $config['user'], $config['password'], $config['dbname'],$config['charset']);
  45. }
  46. return self::$instance[$config_name];
  47. }
  48. /**
  49. * 关闭数据库实例
  50. *
  51. * @param string $config_name
  52. */
  53. public static function close($config_name)
  54. {
  55. if (isset(self::$instance[$config_name])) {
  56. self::$instance[$config_name]->closeConnection();
  57. self::$instance[$config_name] = null;
  58. }
  59. }
  60. /**
  61. * 关闭所有数据库实例
  62. */
  63. public static function closeAll()
  64. {
  65. foreach (self::$instance as $connection) {
  66. $connection->closeConnection();
  67. }
  68. self::$instance = array();
  69. }
  70. }