1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* @link http://www.yiiframework.com/ |
4
|
|
|
* @copyright Copyright (c) 2008 Yii Software LLC |
5
|
|
|
* @license http://www.yiiframework.com/license/ |
6
|
|
|
*/ |
7
|
|
|
|
8
|
|
|
namespace yii\di; |
9
|
|
|
|
10
|
|
|
use yii\di\exceptions\CircularReferenceException; |
11
|
|
|
use yii\di\exceptions\InvalidConfigException; |
12
|
|
|
use yii\di\exceptions\NotFoundException; |
13
|
|
|
use yii\di\exceptions\NotInstantiableException; |
14
|
|
|
|
15
|
|
|
/** |
16
|
|
|
* Container implements a [dependency injection](http://en.wikipedia.org/wiki/Dependency_injection) container. |
17
|
|
|
* |
18
|
|
|
* @author Alexander Makarov <[email protected]> |
19
|
|
|
* @since 1.0 |
20
|
|
|
*/ |
21
|
|
|
class Container extends AbstractContainer |
22
|
|
|
{ |
23
|
|
|
/** |
24
|
|
|
* @var object[] |
25
|
|
|
*/ |
26
|
|
|
private $instances; |
27
|
|
|
|
28
|
|
|
public function set(string $id, $definition): void |
29
|
|
|
{ |
30
|
|
|
$this->instances[$id] = null; |
31
|
|
|
|
32
|
|
|
parent::set($id, $definition); |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
/** |
36
|
|
|
* Returns an instance by either interface name or alias. |
37
|
|
|
* |
38
|
|
|
* Same instance of the class will be returned each time this method is called. |
39
|
|
|
* |
40
|
|
|
* @param string $id the interface name or an alias name (e.g. `foo`) that was previously registered via [[set()]]. |
41
|
|
|
* @return object an instance of the requested interface. |
42
|
|
|
* @throws CircularReferenceException |
43
|
|
|
* @throws InvalidConfigException |
44
|
|
|
* @throws NotFoundException |
45
|
|
|
* @throws NotInstantiableException |
46
|
|
|
*/ |
47
|
|
|
public function get($id) |
48
|
|
|
{ |
49
|
|
|
$id = $this->dereference($id); |
50
|
|
|
|
51
|
|
|
if (isset($this->instances[$id])) { |
52
|
|
|
return $this->instances[$id]; |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
$object = $this->build($id); |
56
|
|
|
$this->instances[$id] = $object; |
57
|
|
|
|
58
|
|
|
return $this->initObject($object); |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
/** |
62
|
|
|
* Returns a value indicating whether the container has already instantiated |
63
|
|
|
* instance of the specified name. |
64
|
|
|
* @param string $id class name, interface name or alias name |
65
|
|
|
* @return bool whether the container has instance of id specified. |
66
|
|
|
* @throws CircularReferenceException |
67
|
|
|
*/ |
68
|
|
|
public function hasInstance($id): bool |
69
|
|
|
{ |
70
|
|
|
$id = $this->dereference($id); |
71
|
|
|
|
72
|
|
|
return isset($this->instances[$id]); |
73
|
|
|
} |
74
|
|
|
|
75
|
|
|
/** |
76
|
|
|
* Returns all instances set in container |
77
|
|
|
* @return array list of instance |
78
|
|
|
*/ |
79
|
|
|
public function getInstances() : array |
80
|
|
|
{ |
81
|
|
|
return $this->instances; |
82
|
|
|
} |
83
|
|
|
} |
84
|
|
|
|