Db.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. /**
  16. * 数据库类
  17. */
  18. class Db
  19. {
  20. /**
  21. * 实例数组
  22. * @var array
  23. */
  24. protected static $instance = array();
  25. /**
  26. * 获取实例
  27. * @param string $config_name
  28. * @throws \Exception
  29. */
  30. public static function instance($config_name)
  31. {
  32. if(!isset(\Config\Db::$$config_name))
  33. {
  34. echo "\\Config\\Db::$config_name not set\n";
  35. throw new \Exception("\\Config\\Db::$config_name not set\n");
  36. }
  37. if(empty(self::$instance[$config_name]))
  38. {
  39. $config = \Config\Db::$$config_name;
  40. self::$instance[$config_name] = new \GatewayWorker\Lib\DbConnection($config['host'], $config['port'], $config['user'], $config['password'], $config['dbname']);
  41. }
  42. return self::$instance[$config_name];
  43. }
  44. /**
  45. * 关闭数据库实例
  46. * @param string $config_name
  47. */
  48. public static function close($config_name)
  49. {
  50. if(isset(self::$instance[$config_name]))
  51. {
  52. self::$instance[$config_name]->closeConnection();
  53. self::$instance[$config_name] = null;
  54. }
  55. }
  56. /**
  57. * 关闭所有数据库实例
  58. */
  59. public static function closeAll()
  60. {
  61. foreach(self::$instance as $connection)
  62. {
  63. $connection->closeConnection();
  64. }
  65. self::$instance = array();
  66. }
  67. }