1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Gr8abbasi\Container; |
4
|
|
|
|
5
|
|
|
use Interop\Container\ContainerInterface; |
6
|
|
|
use Gr8abbasi\Container\Exception\NotFoundException; |
7
|
|
|
use Gr8abbasi\Container\Exception\ContainerException; |
8
|
|
|
|
9
|
|
|
/** |
10
|
|
|
* Container Class |
11
|
|
|
*/ |
12
|
|
|
class Container implements ContainerInterface |
13
|
|
|
{ |
14
|
|
|
/** |
15
|
|
|
* @var array |
16
|
|
|
*/ |
17
|
|
|
private $services; |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* @var array |
21
|
|
|
*/ |
22
|
|
|
private $serviceStore; |
23
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* Constructor for Container |
26
|
|
|
* |
27
|
|
|
* @param array $services |
28
|
|
|
*/ |
29
|
4 |
|
public function __construct(array $services = []) |
30
|
|
|
{ |
31
|
4 |
|
$this->services = $services; |
32
|
4 |
|
$this->serviceStore = []; |
33
|
4 |
|
} |
34
|
|
|
|
35
|
|
|
/** |
36
|
|
|
* {@inheritdoc} |
37
|
|
|
*/ |
38
|
3 |
|
public function get($name) |
39
|
|
|
{ |
40
|
3 |
|
if (!$this->has($name)) { |
41
|
1 |
|
throw new NotFoundException('Service not found: ' . $name); |
42
|
|
|
} |
43
|
|
|
|
44
|
2 |
|
if (!isset($this->serviceStore[$name])) { |
45
|
2 |
|
$this->serviceStore[$name] = $this->createService($name); |
46
|
1 |
|
} |
47
|
|
|
|
48
|
1 |
|
return $this->serviceStore[$name]; |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
/** |
52
|
|
|
* {@inheritdoc} |
53
|
|
|
*/ |
54
|
3 |
|
public function has($name) |
55
|
|
|
{ |
56
|
3 |
|
return isset($this->services[$name]); |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
/** |
60
|
|
|
* Create service instance |
61
|
|
|
* |
62
|
|
|
* @param string $name |
63
|
|
|
* |
64
|
|
|
* @return mixed created service |
65
|
|
|
*/ |
66
|
2 |
|
private function createService($name) |
67
|
|
|
{ |
68
|
2 |
|
if (!isset($this->services[$name]) || empty($this->services[$name])) { |
69
|
1 |
|
throw new ContainerException( |
70
|
|
|
'Service should be an array with key value pair: ' . $name |
71
|
1 |
|
); |
72
|
|
|
} |
73
|
|
|
|
74
|
1 |
|
if (!class_exists($this->services[$name]['class'])) { |
75
|
|
|
throw new ContainerException( |
76
|
|
|
'Class does not exists: ' . $this->services[$name]['class'] |
77
|
|
|
); |
78
|
|
|
} |
79
|
|
|
|
80
|
1 |
|
$service = new \ReflectionClass($this->services[$name]['class']); |
81
|
1 |
|
return $service->newInstance(); |
82
|
|
|
} |
83
|
|
|
} |
84
|
|
|
|