1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/** |
4
|
|
|
* Phoole (PHP7.2+) |
5
|
|
|
* |
6
|
|
|
* @category Library |
7
|
|
|
* @package Phoole\Di |
8
|
|
|
* @copyright Copyright (c) 2019 Hong Zhang |
9
|
|
|
*/ |
10
|
|
|
declare(strict_types=1); |
11
|
|
|
|
12
|
|
|
namespace Phoole\Di; |
13
|
|
|
|
14
|
|
|
use Psr\Container\ContainerInterface; |
15
|
|
|
use Phoole\Di\Exception\RuntimeException; |
16
|
|
|
use Phoole\Di\Exception\NotFoundException; |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* Service |
20
|
|
|
* |
21
|
|
|
* A static service locator build around the `container` |
22
|
|
|
* |
23
|
|
|
* ```php |
24
|
|
|
* // set the container first |
25
|
|
|
* Service::setContainer($container); |
26
|
|
|
* |
27
|
|
|
* // get shared 'db' service |
28
|
|
|
* $db = Service::get('db'); |
29
|
|
|
* |
30
|
|
|
* // get a new 'db' service |
31
|
|
|
* $dbNew = Service::get('db@'); |
32
|
|
|
* ``` |
33
|
|
|
* |
34
|
|
|
* @package Phoole\Di |
35
|
|
|
*/ |
36
|
|
|
class Service |
37
|
|
|
{ |
38
|
|
|
/** |
39
|
|
|
* @var ContainerInterface |
40
|
|
|
* @staticvar |
41
|
|
|
*/ |
42
|
|
|
protected static $container; |
43
|
|
|
|
44
|
|
|
/** |
45
|
|
|
* Finalized constructor to prevent instantiation. |
46
|
|
|
* |
47
|
|
|
* @access private |
48
|
|
|
* @final |
49
|
|
|
*/ |
50
|
|
|
final private function __construct() |
51
|
|
|
{ |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
/** |
55
|
|
|
* Locate a service from the container |
56
|
|
|
* |
57
|
|
|
* @param string $id service id |
58
|
|
|
* @return object |
59
|
|
|
* @throws NotFoundException if container not set or object not found |
60
|
|
|
* @throws RuntimeException if object instantiation error |
61
|
|
|
*/ |
62
|
|
|
public static function get(string $id): object |
63
|
|
|
{ |
64
|
|
|
if (static::$container) { |
65
|
|
|
return static::$container->get($id); |
66
|
|
|
} |
67
|
|
|
throw new RuntimeException(__CLASS__ . ": container not set"); |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
/** |
71
|
|
|
* Set the container |
72
|
|
|
* |
73
|
|
|
* @param ContainerInterface $container |
74
|
|
|
* @return void |
75
|
|
|
* @throws RuntimeException if container set already |
76
|
|
|
*/ |
77
|
|
|
public static function setContainer(ContainerInterface $container = null): void |
78
|
|
|
{ |
79
|
|
|
if (null === static::$container) { |
80
|
|
|
static::$container = $container; |
81
|
|
|
} elseif (is_null($container)) { |
82
|
|
|
static::$container = null; |
83
|
|
|
} else { |
84
|
|
|
throw new RuntimeException(__CLASS__ . ": container set already"); |
85
|
|
|
} |
86
|
|
|
} |
87
|
|
|
} |
88
|
|
|
|