colly_wyx
2017-08-10 2e53366717ad57da1a9dd6dc71a69c078961ad74
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
<?php
 
/**
 * 服务定位器[暂定版]
 */
class System_Service_Locator{
 
    protected $_components; //保存组件实例
    protected $_definitions; //保存组件定义
    public static $instance;
 
    public static function getInstance(){
        if(self::$instance){
            return self::$instance;
        }
        return self::$instance = new self;
    }
 
    public function __get($name)
    {
        return $this->get($name);
    }
 
    /**
     * 注册服务
     * @param $name
     * @param $definition
     */
    public function set($name, $definition)
    {
        if(is_string($definition) || is_object($definition) || is_callable($definition, true)) {
            $this->_definitions[$name] = $definition;
        }else{
            throw new InvalidArgumentException('Invalid definition.');
        }
    }
 
    /**
     * 数组方式注册服务
     * @param [type] $definitions [description]
     */
    public function setByArrs($definitions){
        foreach ($components as $id => $definition) {
            $this->set($id, $definition);
        }
    }
 
    /**
     * 读取服务
     * @param $name
     * @return mixed
     */
    public function get($name)
    {
        if(isset($this->_components[$name])){
            return $this->_components[$name];
        }
 
        if(!isset($this->_definitions[$name])){
           return false;
        }
 
        if(is_string($this->_definitions[$name]) && class_exists($this->_definitions[$name])){
            return $this->_components[$name] = new $this->_definitions[$name];
        }
 
        if(is_callable($this->_definitions[$name], true)){
            return $this->_components[$name] = call_user_func_array($this->_definitions[$name], []);
        }
 
        throw new InvalidArgumentException("Undefined service $name");
    }
 
    /**
     * @param $name
     * @return bool
     */
    public function has($name)
    {
        return isset($this->_definitions[$name]);
    }
 
    /**
     * @param $name
     */
    public function clear($name)
    {
        unset($this->_components[$name], $this->_definitions[$name]);
    }
 
    /**
     * @return mixed
     */
    public function getComponents()
    {
        return $this->_components;
    }
 
    /**
     * @return mixed
     */
    public function getDefintions()
    {
        return $this->_definitions;
    }
}