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\Util; |
13
|
|
|
|
14
|
|
|
use Phoole\Config\ConfigInterface; |
15
|
|
|
use Psr\Container\ContainerInterface; |
16
|
|
|
|
17
|
|
|
/** |
18
|
|
|
* ExtendedContainerTrait |
19
|
|
|
* |
20
|
|
|
* Implementing ExtendedContainerInterface |
21
|
|
|
* |
22
|
|
|
* @package Phoole\Di |
23
|
|
|
*/ |
24
|
|
|
trait ExtendedContainerTrait |
25
|
|
|
{ |
26
|
|
|
use ContainerTrait; |
27
|
|
|
|
28
|
|
|
/** |
29
|
|
|
* init the container |
30
|
|
|
* |
31
|
|
|
* @param ConfigInterface $config |
32
|
|
|
* @param ContainerInterface $delegator |
33
|
|
|
* @return void |
34
|
|
|
*/ |
35
|
|
|
protected function initContainer( |
36
|
|
|
ConfigInterface $config, |
37
|
|
|
ContainerInterface $delegator = null |
38
|
|
|
): void { |
39
|
|
|
$this->config = $config; |
40
|
|
|
$this->delegator = $delegator ?? $this; |
41
|
|
|
|
42
|
|
|
// some predefined objects |
43
|
|
|
$this->objects['config'] = $this->config; |
44
|
|
|
$this->objects['container'] = $this->delegator; |
45
|
|
|
|
46
|
|
|
// run the code |
47
|
|
|
$settings = &($this->config->getTree())->get(''); |
48
|
|
|
$this->setReferencePattern('${#', '}'); |
49
|
|
|
$this->deReference($settings); |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
/** |
53
|
|
|
* {@inheritDoc} |
54
|
|
|
*/ |
55
|
|
|
public function resolve(&$input): void |
56
|
|
|
{ |
57
|
|
|
// check param first |
58
|
|
|
$this->config->deReference($input); |
59
|
|
|
|
60
|
|
|
// then the objects |
61
|
|
|
$this->deReference($input); |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
/** |
65
|
|
|
* {@inheritDoc} |
66
|
|
|
*/ |
67
|
|
|
public function call($callable, array $arguments = []) |
68
|
|
|
{ |
69
|
|
|
$this->resolve($callable); |
70
|
|
|
$this->resolve($arguments); |
71
|
|
|
|
72
|
|
|
if (is_callable($callable)) { |
73
|
|
|
return call_user_func($callable, $arguments); |
74
|
|
|
} else { |
75
|
|
|
throw new RuntimeException("Callable error"); |
76
|
|
|
} |
77
|
|
|
} |
78
|
|
|
|
79
|
|
|
/** |
80
|
|
|
* {@inheritDoc} |
81
|
|
|
*/ |
82
|
|
|
public function draw(string $id, array $args = []): object |
83
|
|
|
{ |
84
|
|
|
if ($this->has($id)) { |
|
|
|
|
85
|
|
|
return $this->newInstance($id, $args); |
86
|
|
|
} else { |
87
|
|
|
throw new NotFoundException("Service $id not found"); |
88
|
|
|
} |
89
|
|
|
} |
90
|
|
|
} |
91
|
|
|
|
This check looks for methods that are used by a trait but not required by it.
To illustrate, let’s look at the following code example
The trait
Idable
provides a methodequalsId
that in turn relies on the methodgetId()
. If this method does not exist on a class mixing in this trait, the method will fail.Adding the
getId()
as an abstract method to the trait will make sure it is available.