Config.php 963 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. <?php
  2. namespace Core;
  3. /**
  4. * 配置文件的加载 基于ArrayAccess
  5. * 可以让对象像数组一样进行访问
  6. * Class Config
  7. * @package IMooc
  8. */
  9. class Config implements \ArrayAccess
  10. {
  11. protected $path;
  12. protected $configs = array();
  13. function __construct($path)
  14. {
  15. $this->path = $path;
  16. }
  17. /**
  18. * 获取配置
  19. * @param mixed $key
  20. * @return mixed
  21. */
  22. function offsetGet($key)
  23. {
  24. if (empty($this->configs[$key]))
  25. {
  26. $file_path = $this->path.'/'.$key.'.php';
  27. $config = require $file_path;
  28. $this->configs[$key] = $config;
  29. }
  30. return $this->configs[$key];
  31. }
  32. function offsetSet($key, $value)
  33. {
  34. throw new \Exception("cannot write config file.");
  35. }
  36. function offsetExists($key)
  37. {
  38. return isset($this->configs[$key]);
  39. }
  40. function offsetUnset($key)
  41. {
  42. unset($this->configs[$key]);
  43. }
  44. }