colly_wyx
2018-05-18 50a53f7db63c5729b0ddbc93367117cf35ccf03c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
<?php 
/**
 * PhalApi_Config_File 文件配置类
 *
 * <li>从配置文件获取参数配置</li>
 * 
 * 使用示例:
 * <br>
 * <code>
 *         $config = new PhalApi_Config_File('./Config');
 *         $config->get('sys.db.user');
 * </code>
 *
 * @package     PhalApi\Config
 * @see         PhalApi_Config::get()
 * @license     http://www.phalapi.net/license GPL 协议
 * @link        http://www.phalapi.net/
 * @author      dogstar <chanzonghuang@gmail.com> 2014-10-02
 */
 
class PhalApi_Config_File implements PhalApi_Config {
 
    /**
     * @var string $path 配置文件的目录位置
     */
    private $path = '';
    
    /**
     * @var array $map 配置文件的映射表,避免重复加载 
     */
    private $map = array();
    
    public function __construct($configPath) {
        $this->path = $configPath;
    }
    
    /**
     * 获取配置
     * 首次获取时会进行初始化
     *
     * @param $key string 配置键值
     * @return mixed 需要获取的配置值
     */
    public function get($key, $default = NULL) {
        $keyArr = explode('.', $key);
        $fileName = $keyArr[0];
        
        if (!isset($this->map[$fileName])) {
            $this->loadConfig($fileName);
        }
        
        $rs = NULL;
        $preRs = $this->map;
        foreach ($keyArr as $subKey) {
            if (!isset($preRs[$subKey])) {
                $rs = NULL;
                break;
            }
            $rs = $preRs[$subKey];
            $preRs = $rs;
        }
        
        return $rs !== NULL ? $rs : $default;
    }
    
    /**
     * 加载配置文件
     * 加载保存配置信息数组的config.php文件,若文件不存在,则将$map置为空数组
     *
     * @param string $fileName 配置文件路径
     * @return array 配置文件对应的内容
     */
    private function loadConfig($fileName) {
        $config = include($this->path . DIRECTORY_SEPARATOR . $fileName . '.php');
        
        $this->map[$fileName] = $config;
    }
}