|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace PhpCache\ServiceManager; |
|
4
|
|
|
|
|
5
|
|
|
use PhpCache\ServiceManager\Exception\NotFoundException; |
|
6
|
|
|
use Psr\Container\ContainerInterface; |
|
7
|
|
|
|
|
8
|
|
|
/** |
|
9
|
|
|
* Description of ServiceManager. |
|
10
|
|
|
* |
|
11
|
|
|
* @author dude920228 |
|
12
|
|
|
*/ |
|
13
|
|
|
class ServiceManager implements ContainerInterface |
|
14
|
|
|
{ |
|
15
|
|
|
private $aliases; |
|
16
|
|
|
private $config; |
|
17
|
|
|
private $factories; |
|
18
|
|
|
private $invokables; |
|
19
|
|
|
|
|
20
|
|
|
public function __construct($config) |
|
21
|
|
|
{ |
|
22
|
|
|
$this->config = $config; |
|
23
|
|
|
$this->configure(); |
|
24
|
|
|
} |
|
25
|
|
|
|
|
26
|
|
|
private function configure() |
|
27
|
|
|
{ |
|
28
|
|
|
if (isset($this->config['services']['aliases'])) { |
|
29
|
|
|
$this->aliases = $this->config['services']['aliases']; |
|
30
|
|
|
} else { |
|
31
|
|
|
$this->aliases = []; |
|
32
|
|
|
} |
|
33
|
|
|
if (isset($this->config['services']['factories'])) { |
|
34
|
|
|
$this->factories = $this->config['services']['factories']; |
|
35
|
|
|
} else { |
|
36
|
|
|
$this->factories = []; |
|
37
|
|
|
} |
|
38
|
|
|
if (isset($this->config['services']['invokables'])) { |
|
39
|
|
|
$this->invokables = $this->config['services']['invokables']; |
|
40
|
|
|
} else { |
|
41
|
|
|
$this->invokables = []; |
|
42
|
|
|
} |
|
43
|
|
|
} |
|
44
|
|
|
|
|
45
|
|
|
public function get($id) |
|
46
|
|
|
{ |
|
47
|
|
|
if ($this->has($id)) { |
|
48
|
|
|
$serviceType = $this->getServiceType($id); |
|
49
|
|
|
if($serviceType == 'alias') { |
|
50
|
|
|
$service = $this->aliases[$id];; |
|
51
|
|
|
return $this->get($service); |
|
52
|
|
|
} |
|
53
|
|
|
if ($serviceType == 'factory') { |
|
54
|
|
|
return (new $this->factories[$id]())($this); |
|
55
|
|
|
} |
|
56
|
|
|
if ($serviceType == 'invokable') { |
|
57
|
|
|
return new $this->invokables[$id](); |
|
58
|
|
|
} |
|
59
|
|
|
} |
|
60
|
|
|
|
|
61
|
|
|
throw new NotFoundException( |
|
62
|
|
|
sprintf('Service "%s" couldn\'t be created! Reason: service not found', $id) |
|
63
|
|
|
); |
|
64
|
|
|
} |
|
65
|
|
|
|
|
66
|
|
|
private function getServiceType($id) |
|
67
|
|
|
{ |
|
68
|
|
|
if (array_key_exists($id, $this->aliases)) { |
|
69
|
|
|
return 'alias'; |
|
70
|
|
|
} |
|
71
|
|
|
|
|
72
|
|
|
return array_key_exists($id, $this->factories) ? 'factory' : 'invokable'; |
|
73
|
|
|
} |
|
74
|
|
|
|
|
75
|
|
|
public function getConfig() |
|
76
|
|
|
{ |
|
77
|
|
|
return $this->config['config']; |
|
78
|
|
|
} |
|
79
|
|
|
|
|
80
|
|
|
public function has($id) |
|
81
|
|
|
{ |
|
82
|
|
|
return array_key_exists($id, $this->aliases) || |
|
83
|
|
|
array_key_exists($id, $this->factories) || |
|
84
|
|
|
array_key_exists($id, $this->invokables); |
|
85
|
|
|
} |
|
86
|
|
|
} |
|
87
|
|
|
|