1
|
|
|
<?php |
2
|
|
|
namespace Yiisoft\Di\Support; |
3
|
|
|
|
4
|
|
|
use Yiisoft\Di\Contracts\DeferredServiceProviderInterface; |
5
|
|
|
|
6
|
|
|
/** |
7
|
|
|
* Base class for service providers that should be deferred to register till services are |
8
|
|
|
* actually required. |
9
|
|
|
* |
10
|
|
|
* Complex services with heavy dependencies might create redundant load during bootstrapping |
11
|
|
|
* of an application so to reduce actions performed during the container bootstrap you can |
12
|
|
|
* |
13
|
|
|
* Deferred providers can be added to the Container like basic providers but won't register |
14
|
|
|
* any definitions to the container till one of the classes listed in `provides` method would |
15
|
|
|
* be requested from container. Example: |
16
|
|
|
* |
17
|
|
|
* ```php |
18
|
|
|
* use Yiisoft\Di\Support\DeferredServiceProvider; |
19
|
|
|
* |
20
|
|
|
* class CarProvider extends DeferredServiceProvider |
21
|
|
|
* { |
22
|
|
|
* public function provides(): array |
23
|
|
|
* { |
24
|
|
|
* return [ |
25
|
|
|
* Car::class, |
26
|
|
|
* CarFactory::class, |
27
|
|
|
* ]; |
28
|
|
|
* } |
29
|
|
|
* |
30
|
|
|
* public function register(): void |
31
|
|
|
* { |
32
|
|
|
* $container = $this->container; |
33
|
|
|
* |
34
|
|
|
* $container->set(Car::class, Car::class); |
35
|
|
|
* $container->set(CarFactory::class, CarFactory::class); |
36
|
|
|
* $container->set(EngineInterface::class, EngineMarkOne::class); |
37
|
|
|
* } |
38
|
|
|
* } |
39
|
|
|
* |
40
|
|
|
* $container->addProvider(CarProvider::class); |
41
|
|
|
* |
42
|
|
|
* $container->has(EngineInterface::class); // returns false provider wasn't registered |
43
|
|
|
* |
44
|
|
|
* $engine = $container->get(EngineInterface::class); // returns EngineMarkOne as provider was |
45
|
|
|
* // registered once EngineInterface was requested from the container. |
46
|
|
|
* ``` |
47
|
|
|
*/ |
48
|
|
|
abstract class DeferredServiceProvider implements DeferredServiceProviderInterface |
49
|
|
|
{ |
50
|
|
|
/** |
51
|
|
|
* Lists classes provided by service provider. Should be a list of class names |
52
|
|
|
* or identifiers. Example: |
53
|
|
|
* |
54
|
|
|
* ```php |
55
|
|
|
* return [ |
56
|
|
|
* Car::class, |
57
|
|
|
* EngineInterface::class, |
58
|
|
|
* 'car-factory', |
59
|
|
|
* ]; |
60
|
|
|
* ``` |
61
|
|
|
* |
62
|
|
|
* @return array list of provided classes. |
63
|
|
|
*/ |
64
|
|
|
abstract public function provides(): array; |
65
|
|
|
|
66
|
|
|
/** |
67
|
|
|
* Identifies whether service provider would register definition for |
68
|
|
|
* given identifier or not. |
69
|
|
|
* |
70
|
|
|
* @param string $id class, interface or identifier in the Container. |
71
|
|
|
* @return bool whether service provider would register definition or not. |
72
|
|
|
*/ |
73
|
|
|
public function hasDefinitionFor(string $id): bool |
74
|
|
|
{ |
75
|
|
|
return \in_array($id, $this->provides(), true); |
76
|
|
|
} |
77
|
|
|
} |
78
|
|
|
|