1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* This file is part of the Yep package. |
4
|
|
|
* Copyright (c) 2018 Martin Zeman (Zemistr) (http://www.zemistr.eu) |
5
|
|
|
*/ |
6
|
|
|
|
7
|
|
|
namespace Yep\Container; |
8
|
|
|
|
9
|
|
|
use Yep\Container\Exception\ServiceMustBeAnObjectException; |
10
|
|
|
use Yep\Container\Exception\ServiceNotFoundException; |
11
|
|
|
|
12
|
|
|
trait ContainerTrait |
13
|
|
|
{ |
14
|
|
|
protected $parameters = []; |
15
|
|
|
protected $services = []; |
16
|
|
|
|
17
|
4 |
|
public function __construct(array $parameters = []) |
18
|
|
|
{ |
19
|
4 |
|
$this->parameters = $parameters; |
20
|
4 |
|
} |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* @param string $key |
24
|
|
|
* @param mixed $value |
25
|
|
|
*/ |
26
|
1 |
|
public function setParameter($key, $value) |
27
|
|
|
{ |
28
|
1 |
|
$this->parameters[$key] = $value; |
29
|
1 |
|
} |
30
|
|
|
|
31
|
|
|
/** |
32
|
|
|
* @param string $key |
33
|
|
|
* @param mixed $default |
34
|
|
|
* @return mixed |
35
|
|
|
*/ |
36
|
1 |
|
public function getParameter($key, $default = null) |
37
|
|
|
{ |
38
|
1 |
|
if (isset($this->parameters[$key])) { |
39
|
1 |
|
return $this->parameters[$key]; |
40
|
|
|
} |
41
|
|
|
|
42
|
1 |
|
return $default; |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
/** |
46
|
|
|
* @param string $name |
47
|
|
|
* @param object $service |
48
|
|
|
* @return mixed |
49
|
|
|
* @throws ServiceMustBeAnObjectException |
50
|
|
|
*/ |
51
|
3 |
|
public function setService($name, $service) |
52
|
|
|
{ |
53
|
3 |
|
if (!is_object($service)) { |
54
|
2 |
|
throw ServiceMustBeAnObjectException::create($service); |
55
|
|
|
} |
56
|
|
|
|
57
|
1 |
|
return $this->services[$name] = $service; |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
/** |
61
|
|
|
* @param string $name |
62
|
|
|
* @return mixed |
63
|
|
|
* @throws ServiceMustBeAnObjectException |
64
|
|
|
* @throws ServiceNotFoundException |
65
|
|
|
*/ |
66
|
3 |
|
public function getService($name) |
67
|
|
|
{ |
68
|
3 |
|
if (isset($this->services[$name])) { |
69
|
1 |
|
return $this->services[$name]; |
70
|
|
|
} |
71
|
|
|
|
72
|
3 |
|
if (!method_exists($this, $name.'Factory')) { |
73
|
1 |
|
throw ServiceNotFoundException::create($name); |
74
|
|
|
} |
75
|
|
|
|
76
|
2 |
|
$service = $this->{$name.'Factory'}(); |
77
|
|
|
|
78
|
2 |
|
return $this->setService($name, $service); |
79
|
|
|
} |
80
|
|
|
} |
81
|
|
|
|