-
Notifications
You must be signed in to change notification settings - Fork 0
/
ContainerAwareTrait.php
87 lines (77 loc) · 1.76 KB
/
ContainerAwareTrait.php
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
84
85
86
87
<?php
namespace Rad\DependencyInjection;
use BadMethodCallException;
use Rad\Utility\Inflection;
trait ContainerAwareTrait
{
/**
* @var Container
*/
protected $container;
/**
* Set container
*
* @param Container $container
*/
public function setContainer(Container $container)
{
$this->container = $container;
}
/**
* Get container
*
* @return Container
*/
public function getContainer()
{
if (!is_object($this->container)) {
return $this->container = Container::getInstance();
}
return $this->container;
}
/**
* Magic call
*
* @param string $method
* @param array $args
*
* @return mixed|object
* @throws BadMethodCallException
* @throws Exception
*/
public function __call($method, $args)
{
if (stripos($method, 'get', 0) !== false) {
return $this->getContainer()->get(Inflection::underscore(substr($method, 3)), $args);
} else {
throw new BadMethodCallException(sprintf('Method "%s" does not exist.', $method));
}
}
/**
* Magic get
*
* @param string $property Service name
*
* @return mixed
*/
public function __get($property)
{
return $this->get($property);
}
/**
* Get service
*
* @param string $serviceName Service name
* @param array $args
*
* @return mixed|null|object
* @throws Exception\ServiceNotFoundException
*/
public function get($serviceName, array $args = [])
{
if ($this->getContainer()->has($serviceName)) {
return $this->getContainer()->get($serviceName, $args);
}
return null;
}
}