blob: d8b9063e71b950bd11d9b1f12ca8f663fdab222d (
plain)
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
|
<?php
namespace Core;
use RuntimeException;
/**
* The registry class is a dependency injection container
*
* @property mixed db
* @property mixed event
* @package core
* @author Frederic Guillot
*/
class Registry
{
/**
* Contains all dependencies
*
* @access private
* @var array
*/
private $container = array();
/**
* Contains all instances
*
* @access private
* @var array
*/
private $instances = array();
/**
* Set a dependency
*
* @access public
* @param string $name Unique identifier for the service/parameter
* @param mixed $value The value of the parameter or a closure to define an object
*/
public function __set($name, $value)
{
$this->container[$name] = $value;
}
/**
* Get a dependency
*
* @access public
* @param string $name Unique identifier for the service/parameter
* @return mixed The value of the parameter or an object
* @throws RuntimeException If the identifier is not found
*/
public function __get($name)
{
if (isset($this->container[$name])) {
if (is_callable($this->container[$name])) {
return $this->container[$name]();
}
else {
return $this->container[$name];
}
}
throw new \RuntimeException('Identifier not found in the registry: '.$name);
}
/**
* Return a shared instance of a dependency
*
* @access public
* @param string $name Unique identifier for the service/parameter
* @return mixed Same object instance of the dependency
*/
public function shared($name)
{
if (! isset($this->instances[$name])) {
$this->instances[$name] = $this->$name;
}
return $this->instances[$name];
}
}
|