|
1
|
|
|
<?php |
|
2
|
|
|
namespace Mouf\Picotainer; |
|
3
|
|
|
|
|
4
|
|
|
use Interop\Container\ContainerInterface; |
|
5
|
|
|
|
|
6
|
|
|
/** |
|
7
|
|
|
* This class is a minimalist dependency injection container. |
|
8
|
|
|
* It has compatibility with container-interop's ContainerInterface and delegate-lookup feature. |
|
9
|
|
|
* |
|
10
|
|
|
* @author David Négrier <[email protected]> |
|
11
|
|
|
*/ |
|
12
|
|
|
class Picotainer implements ContainerInterface |
|
13
|
|
|
{ |
|
14
|
|
|
|
|
15
|
|
|
/** |
|
16
|
|
|
* The delegate lookup. |
|
17
|
|
|
* |
|
18
|
|
|
* @var ContainerInterface |
|
19
|
|
|
*/ |
|
20
|
|
|
protected $delegateLookupContainer; |
|
21
|
|
|
|
|
22
|
|
|
/** |
|
23
|
|
|
* The array of closures defining each entry of the container. |
|
24
|
|
|
* |
|
25
|
|
|
* @var array<string, Closure> |
|
26
|
|
|
*/ |
|
27
|
|
|
protected $callbacks; |
|
28
|
|
|
|
|
29
|
|
|
/** |
|
30
|
|
|
* The array of entries once they have been instantiated. |
|
31
|
|
|
* |
|
32
|
|
|
* @var array<string, mixed> |
|
33
|
|
|
*/ |
|
34
|
|
|
protected $objects; |
|
35
|
|
|
|
|
36
|
|
|
/** |
|
37
|
|
|
* Instantiate the container. |
|
38
|
|
|
* |
|
39
|
|
|
* @param array<string, Closure> $entries Entries must be passed as an array of anonymous functions. |
|
40
|
|
|
* @param ContainerInterface $delegateLookupContainer Optional delegate lookup container. |
|
41
|
|
|
*/ |
|
42
|
|
|
public function __construct(array $entries, ContainerInterface $delegateLookupContainer = null) |
|
43
|
|
|
{ |
|
44
|
|
|
$this->callbacks = $entries; |
|
45
|
|
|
$this->delegateLookupContainer = $delegateLookupContainer ?: $this; |
|
46
|
|
|
} |
|
47
|
|
|
|
|
48
|
|
|
/* (non-PHPdoc) |
|
49
|
|
|
* @see \Interop\Container\ContainerInterface::get() |
|
50
|
|
|
*/ |
|
51
|
|
|
public function get($identifier) |
|
52
|
|
|
{ |
|
53
|
|
|
if (isset($this->objects[$identifier])) { |
|
54
|
|
|
return $this->objects[$identifier]; |
|
55
|
|
|
} |
|
56
|
|
|
if (!isset($this->callbacks[$identifier])) { |
|
57
|
|
|
throw new PicotainerNotFoundException(sprintf('Identifier "%s" is not defined.', $identifier)); |
|
58
|
|
|
} |
|
59
|
|
|
|
|
60
|
|
|
return $this->objects[$identifier] = $this->callbacks[$identifier]($this->delegateLookupContainer); |
|
61
|
|
|
} |
|
62
|
|
|
|
|
63
|
|
|
/* (non-PHPdoc) |
|
64
|
|
|
* @see \Interop\Container\ContainerInterface::has() |
|
65
|
|
|
*/ |
|
66
|
|
|
public function has($identifier) |
|
67
|
|
|
{ |
|
68
|
|
|
return isset($this->callbacks[$identifier]) || isset($this->objects[$identifier]); |
|
69
|
|
|
} |
|
70
|
|
|
} |
|
71
|
|
|
|