Config.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. <?php
  2. namespace Man\Core\Lib;
  3. /**
  4. *
  5. * 配置
  6. * @author walkor
  7. *
  8. */
  9. class Config
  10. {
  11. /**
  12. * 配置文件名称
  13. * @var string
  14. */
  15. public static $filename;
  16. /**
  17. * 配置数据
  18. * @var array
  19. */
  20. public static $config = array();
  21. /**
  22. * 势力
  23. * @var instance of Config
  24. */
  25. protected static $instances = null;
  26. /**
  27. * 构造函数
  28. * @throws \Exception
  29. */
  30. private function __construct()
  31. {
  32. $config_file = WORKERMAN_ROOT_DIR . 'conf/workerman.conf';
  33. if (!file_exists($config_file))
  34. {
  35. throw new \Exception('Configuration file "' . $config_file . '" not found');
  36. }
  37. self::$config['workerman'] = self::parseFile($config_file);
  38. self::$filename = realpath($config_file);
  39. foreach(glob(WORKERMAN_ROOT_DIR . 'conf/conf.d/*.conf') as $config_file)
  40. {
  41. $worker_name = basename($config_file, '.conf');
  42. self::$config[$worker_name] = self::parseFile($config_file);
  43. }
  44. }
  45. /**
  46. * 解析配置文件
  47. * @param string $config_file
  48. * @throws \Exception
  49. */
  50. protected static function parseFile($config_file)
  51. {
  52. $config = parse_ini_file($config_file, true);
  53. if (!is_array($config) || empty($config))
  54. {
  55. throw new \Exception('Invalid configuration format');
  56. }
  57. return $config;
  58. }
  59. /**
  60. * 获取实例
  61. * @return \Man\Core\Lib\instance
  62. */
  63. public static function instance()
  64. {
  65. if (!self::$instances) {
  66. self::$instances = new self();
  67. }
  68. return self::$instances;
  69. }
  70. /**
  71. * 获取配置
  72. * @param string $uri
  73. * @return mixed
  74. */
  75. public static function get($uri)
  76. {
  77. $node = self::$config;
  78. $paths = explode('.', $uri);
  79. while (!empty($paths)) {
  80. $path = array_shift($paths);
  81. if (!isset($node[$path])) {
  82. return null;
  83. }
  84. $node = $node[$path];
  85. }
  86. return $node;
  87. }
  88. /**
  89. * 获取所有的workers
  90. * @return array
  91. */
  92. public static function getAllWorkers()
  93. {
  94. $copy = self::$config;
  95. unset($copy['workerman']);
  96. return $copy;
  97. }
  98. /**
  99. * 重新载入配置
  100. * @return void
  101. */
  102. public static function reload()
  103. {
  104. self::$instances = null;
  105. }
  106. }