1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* Spiral Framework. |
4
|
|
|
* |
5
|
|
|
* @license MIT |
6
|
|
|
* @author Anton Titov (Wolfy-J) |
7
|
|
|
*/ |
8
|
|
|
|
9
|
|
|
namespace Spiral\Core; |
10
|
|
|
|
11
|
|
|
use Interop\Container\ContainerInterface; |
12
|
|
|
|
13
|
|
|
/** |
14
|
|
|
* Basic spiral cell. Automatically detects if "container" property are presented in class or uses |
15
|
|
|
* global container as fallback. |
16
|
|
|
*/ |
17
|
|
|
abstract class Component |
18
|
|
|
{ |
19
|
|
|
/** |
20
|
|
|
* Global/static mainly used to resolve singletons outside of the runtime scope. |
21
|
|
|
* Must be used as fallback only, or not used at all. All spiral components can |
22
|
|
|
* behave well without it. |
23
|
|
|
* |
24
|
|
|
* @var ContainerInterface |
25
|
|
|
*/ |
26
|
|
|
private static $staticContainer = null; |
27
|
|
|
|
28
|
|
|
/** |
29
|
|
|
* Get instance of container associated with given object, uses global container as fallback |
30
|
|
|
* if not. Method generally used by traits. |
31
|
|
|
* |
32
|
|
|
* @return ContainerInterface|null |
33
|
|
|
*/ |
34
|
17 |
|
protected function iocContainer() |
35
|
|
|
{ |
36
|
|
|
if ( |
37
|
17 |
|
property_exists($this, 'container') |
38
|
17 |
|
&& isset($this->container) |
39
|
17 |
|
&& $this->container instanceof ContainerInterface |
40
|
|
|
) { |
41
|
1 |
|
return $this->container; |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
/* |
45
|
|
|
* Technically your code can work without ever being using fallback container, all |
46
|
|
|
* spiral components can do that and only few traits will require few extra parameters. |
47
|
|
|
* |
48
|
|
|
* I'm planning one day (update: DONE) to run spiral as worker and later in async mode (few app |
49
|
|
|
* processes in memory), memory schemas might help a lot by minimizing runtime code by using |
50
|
|
|
* pre-calculated behaviours. |
51
|
|
|
*/ |
52
|
|
|
|
53
|
17 |
|
return self::$staticContainer; |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
/** |
57
|
|
|
* Get/set instance of global/static container, due this method must be used as few times as |
58
|
|
|
* possible both getter and setter methods joined into one. Please use this method only as |
59
|
|
|
* fallback. |
60
|
|
|
* |
61
|
|
|
* @internal Do not use for business logic. |
62
|
|
|
* |
63
|
|
|
* @param ContainerInterface $container Can be set to null. |
64
|
|
|
* |
65
|
|
|
* @return ContainerInterface|null |
66
|
|
|
*/ |
67
|
17 |
|
final protected static function staticContainer(ContainerInterface $container = null) |
68
|
|
|
{ |
69
|
17 |
|
if (func_num_args() === 0) { |
70
|
1 |
|
return self::$staticContainer; |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
//Exchanging values |
74
|
17 |
|
$outer = self::$staticContainer; |
75
|
17 |
|
self::$staticContainer = $container; |
76
|
|
|
|
77
|
|
|
//Return previous container or null |
78
|
17 |
|
return $outer; |
79
|
|
|
} |
80
|
|
|
} |
81
|
|
|
|