1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* Phossa Project |
4
|
|
|
* |
5
|
|
|
* PHP version 5.4 |
6
|
|
|
* |
7
|
|
|
* @category Library |
8
|
|
|
* @package Phossa2\Di |
9
|
|
|
* @copyright Copyright (c) 2016 phossa.com |
10
|
|
|
* @license http://mit-license.org/ MIT License |
11
|
|
|
* @link http://www.phossa.com/ |
12
|
|
|
*/ |
13
|
|
|
/*# declare(strict_types=1); */ |
14
|
|
|
|
15
|
|
|
namespace Phossa2\Di; |
16
|
|
|
|
17
|
|
|
use Phossa2\Di\Message\Message; |
18
|
|
|
use Phossa2\Shared\Base\StaticAbstract; |
19
|
|
|
use Interop\Container\ContainerInterface; |
20
|
|
|
use Phossa2\Di\Exception\RuntimeException; |
21
|
|
|
use Phossa2\Di\Exception\NotFoundException; |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* Service |
25
|
|
|
* |
26
|
|
|
* Provides a service locator building around the container |
27
|
|
|
* |
28
|
|
|
* @package Phossa2\Di |
29
|
|
|
* @author Hong Zhang <[email protected]> |
30
|
|
|
* @version 2.1.0 |
31
|
|
|
* @since 2.1.0 added |
32
|
|
|
*/ |
33
|
|
|
class Service extends StaticAbstract |
34
|
|
|
{ |
35
|
|
|
/** |
36
|
|
|
* @var ContainerInterface |
37
|
|
|
* @access protected |
38
|
|
|
* @staticvar |
39
|
|
|
*/ |
40
|
|
|
protected static $container; |
41
|
|
|
|
42
|
|
|
/** |
43
|
|
|
* Locate a service from the container |
44
|
|
|
* |
45
|
|
|
* ```php |
46
|
|
|
* // the global config object |
47
|
|
|
* $config = Service::config(); |
48
|
|
|
* |
49
|
|
|
* // the container |
50
|
|
|
* $container = Service::container(); |
51
|
|
|
* ``` |
52
|
|
|
* |
53
|
|
|
* @param string $method object id actually |
54
|
|
|
* @param array $params |
55
|
|
|
* @return object |
56
|
|
|
* @throws NotFoundException if container not set or object not found |
57
|
|
|
* @throws RuntimeException if object instantiation error |
58
|
|
|
* @access public |
59
|
|
|
* @api |
60
|
|
|
*/ |
61
|
|
|
public static function __callstatic(/*# string */ $method, array $params) |
62
|
|
|
{ |
63
|
|
|
if (static::$container) { |
64
|
|
|
// append scope if provided |
65
|
|
|
if (!isset($params[0])) { |
66
|
|
|
$method .= '@' . $params[0]; |
67
|
|
|
} |
68
|
|
|
return static::$container->get($method); |
69
|
|
|
} |
70
|
|
|
|
71
|
|
|
// container not set yet |
72
|
|
|
throw new NotFoundException( |
73
|
|
|
Message::get(Message::DI_CONTAINER_NOTFOUND), |
74
|
|
|
Message::DI_CONTAINER_NOTFOUND |
75
|
|
|
); |
76
|
|
|
} |
77
|
|
|
|
78
|
|
|
/** |
79
|
|
|
* Set container |
80
|
|
|
* |
81
|
|
|
* @param ContainerInterface $container |
82
|
|
|
* @access public |
83
|
|
|
* @api |
84
|
|
|
*/ |
85
|
|
|
public function setContainer(ContainerInterface $container) |
86
|
|
|
{ |
87
|
|
|
static::$container = $container; |
88
|
|
|
} |
89
|
|
|
} |
90
|
|
|
|