1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* @link http://www.yiiframework.com/ |
4
|
|
|
* @copyright Copyright (c) 2008 Yii Software LLC |
5
|
|
|
* @license http://www.yiiframework.com/license/ |
6
|
|
|
*/ |
7
|
|
|
|
8
|
|
|
namespace yii\di; |
9
|
|
|
|
10
|
|
|
use ReflectionClass; |
11
|
|
|
use Yii; |
12
|
|
|
use yii\base\Configurable; |
13
|
|
|
use yii\base\Component; |
14
|
|
|
use yii\base\InvalidConfigException; |
15
|
|
|
use yii\helpers\ArrayHelper; |
16
|
|
|
|
17
|
|
|
/** |
18
|
|
|
* Container implements a [dependency injection](http://en.wikipedia.org/wiki/Dependency_injection) container. |
19
|
|
|
* |
20
|
|
|
* A dependency injection (DI) container is an object that knows how to instantiate and configure objects and |
21
|
|
|
* all their dependent objects. For more information about DI, please refer to |
22
|
|
|
* [Martin Fowler's article](http://martinfowler.com/articles/injection.html). |
23
|
|
|
* |
24
|
|
|
* Container supports constructor injection as well as property injection. |
25
|
|
|
* |
26
|
|
|
* To use Container, you first need to set up the class dependencies by calling [[set()]]. |
27
|
|
|
* You then call [[get()]] to create a new class object. Container will automatically instantiate |
28
|
|
|
* dependent objects, inject them into the object being created, configure and finally return the newly created object. |
29
|
|
|
* |
30
|
|
|
* By default, [[\Yii::$container]] refers to a Container instance which is used by [[\Yii::createObject()]] |
31
|
|
|
* to create new object instances. You may use this method to replace the `new` operator |
32
|
|
|
* when creating a new object, which gives you the benefit of automatic dependency resolution and default |
33
|
|
|
* property configuration. |
34
|
|
|
* |
35
|
|
|
* Below is an example of using Container: |
36
|
|
|
* |
37
|
|
|
* ```php |
38
|
|
|
* namespace app\models; |
39
|
|
|
* |
40
|
|
|
* use yii\base\BaseObject; |
41
|
|
|
* use yii\db\Connection; |
42
|
|
|
* use yii\di\Container; |
43
|
|
|
* |
44
|
|
|
* interface UserFinderInterface |
45
|
|
|
* { |
46
|
|
|
* function findUser(); |
47
|
|
|
* } |
48
|
|
|
* |
49
|
|
|
* class UserFinder extends BaseObject implements UserFinderInterface |
50
|
|
|
* { |
51
|
|
|
* public $db; |
52
|
|
|
* |
53
|
|
|
* public function __construct(Connection $db, $config = []) |
54
|
|
|
* { |
55
|
|
|
* $this->db = $db; |
56
|
|
|
* parent::__construct($config); |
57
|
|
|
* } |
58
|
|
|
* |
59
|
|
|
* public function findUser() |
60
|
|
|
* { |
61
|
|
|
* } |
62
|
|
|
* } |
63
|
|
|
* |
64
|
|
|
* class UserLister extends BaseObject |
65
|
|
|
* { |
66
|
|
|
* public $finder; |
67
|
|
|
* |
68
|
|
|
* public function __construct(UserFinderInterface $finder, $config = []) |
69
|
|
|
* { |
70
|
|
|
* $this->finder = $finder; |
71
|
|
|
* parent::__construct($config); |
72
|
|
|
* } |
73
|
|
|
* } |
74
|
|
|
* |
75
|
|
|
* $container = new Container; |
76
|
|
|
* $container->set(\yii\db\Connection::class, [ |
77
|
|
|
* 'dsn' => '...', |
78
|
|
|
* ]); |
79
|
|
|
* $container->set(\app\models\UserFinderInterface::class, [ |
80
|
|
|
* '__class' => \app\models\UserFinder::class, |
81
|
|
|
* ]); |
82
|
|
|
* $container->set('userLister', \app\models\UserLister::class); |
83
|
|
|
* |
84
|
|
|
* $lister = $container->get('userLister'); |
85
|
|
|
* |
86
|
|
|
* // which is equivalent to: |
87
|
|
|
* |
88
|
|
|
* $db = new \yii\db\Connection(['dsn' => '...']); |
89
|
|
|
* $finder = new UserFinder($db); |
90
|
|
|
* $lister = new UserLister($finder); |
91
|
|
|
* ``` |
92
|
|
|
* |
93
|
|
|
* For more details and usage information on Container, see the [guide article on di-containers](guide:concept-di-container). |
94
|
|
|
* |
95
|
|
|
* @property array $definitions The list of the object definitions or the loaded shared objects (type or ID => |
96
|
|
|
* definition or instance). This property is read-only. |
97
|
|
|
* |
98
|
|
|
* @author Qiang Xue <[email protected]> |
99
|
|
|
* @since 2.0 |
100
|
|
|
*/ |
101
|
|
|
class Container extends Component |
102
|
|
|
{ |
103
|
|
|
/** |
104
|
|
|
* @var array singleton objects indexed by their types |
105
|
|
|
*/ |
106
|
|
|
private $_singletons = []; |
107
|
|
|
/** |
108
|
|
|
* @var array object definitions indexed by their types |
109
|
|
|
*/ |
110
|
|
|
private $_definitions = []; |
111
|
|
|
/** |
112
|
|
|
* @var array constructor parameters indexed by object types |
113
|
|
|
*/ |
114
|
|
|
private $_params = []; |
115
|
|
|
/** |
116
|
|
|
* @var array cached ReflectionClass objects indexed by class/interface names |
117
|
|
|
*/ |
118
|
|
|
private $_reflections = []; |
119
|
|
|
/** |
120
|
|
|
* @var array cached dependencies indexed by class/interface names. Each class name |
121
|
|
|
* is associated with a list of constructor parameter types or default values. |
122
|
|
|
*/ |
123
|
|
|
private $_dependencies = []; |
124
|
|
|
/** |
125
|
|
|
* @var array used to collect classes instantiated during get to detect circular references |
126
|
|
|
*/ |
127
|
|
|
private $_getting = []; |
128
|
|
|
|
129
|
|
|
/** |
130
|
|
|
* Returns an instance of the requested class. |
131
|
|
|
* |
132
|
|
|
* You may provide constructor parameters (`$params`) and object configurations (`$config`) |
133
|
|
|
* that will be used during the creation of the instance. |
134
|
|
|
* |
135
|
|
|
* If the class implements [[\yii\base\Configurable]], the `$config` parameter will be passed as the last |
136
|
|
|
* parameter to the class constructor; Otherwise, the configuration will be applied *after* the object is |
137
|
|
|
* instantiated. |
138
|
|
|
* |
139
|
|
|
* Note that if the class is declared to be singleton by calling [[setSingleton()]], |
140
|
|
|
* the same instance of the class will be returned each time this method is called. |
141
|
|
|
* In this case, the constructor parameters and object configurations will be used |
142
|
|
|
* only if the class is instantiated the first time. |
143
|
|
|
* |
144
|
|
|
* @param string $class the class name or an alias name (e.g. `foo`) that was previously registered via [[set()]] |
145
|
|
|
* or [[setSingleton()]]. |
146
|
|
|
* @param array $params a list of constructor parameter values. The parameters should be provided in the order |
147
|
|
|
* they appear in the constructor declaration. If you want to skip some parameters, you should index the remaining |
148
|
|
|
* ones with the integers that represent their positions in the constructor parameter list. |
149
|
|
|
* @param array $config a list of name-value pairs that will be used to initialize the object properties. |
150
|
|
|
* @return object an instance of the requested class. |
151
|
|
|
* @throws InvalidConfigException if the class cannot be recognized or correspond to an invalid definition |
152
|
|
|
* @throws NotInstantiableException If resolved to an abstract class or an interface (since 2.0.9) |
153
|
|
|
*/ |
154
|
3258 |
|
public function get($class, $params = [], $config = []) |
155
|
|
|
{ |
156
|
3258 |
|
if (isset($this->_singletons[$class])) { |
157
|
|
|
// singleton |
158
|
2 |
|
return $this->_singletons[$class]; |
159
|
3258 |
|
} elseif (!isset($this->_definitions[$class])) { |
160
|
3257 |
|
return $this->build($class, $params, $config); |
161
|
|
|
} |
162
|
|
|
|
163
|
26 |
|
if (isset($this->_getting[$class])) { |
164
|
2 |
|
throw new CircularReferenceException($class); |
165
|
|
|
} |
166
|
26 |
|
$this->_getting[$class] = 1; |
167
|
|
|
|
168
|
26 |
|
$definition = $this->_definitions[$class]; |
169
|
|
|
|
170
|
26 |
|
if (is_callable($definition, true)) { |
171
|
3 |
|
$params = $this->resolveDependencies($this->mergeParams($class, $params)); |
172
|
3 |
|
$object = call_user_func($definition, $this, $params, $config); |
173
|
26 |
|
} elseif (is_array($definition)) { |
174
|
26 |
|
$concrete = $definition['__class']; |
175
|
26 |
|
unset($definition['__class']); |
176
|
|
|
|
177
|
26 |
|
$config = array_merge($definition, $config); |
178
|
26 |
|
$params = $this->mergeParams($class, $params); |
179
|
|
|
|
180
|
26 |
|
if ($concrete === $class) { |
181
|
1 |
|
$object = $this->build($class, $params, $config); |
182
|
|
|
} else { |
183
|
26 |
|
$object = $this->get($concrete, $params, $config); |
184
|
|
|
} |
185
|
1 |
|
} elseif (is_object($definition)) { |
186
|
1 |
|
$object = $this->_singletons[$class] = $definition; |
187
|
|
|
} else { |
188
|
|
|
throw new InvalidConfigException('Unexpected object definition type: ' . gettype($definition)); |
189
|
|
|
} |
190
|
|
|
|
191
|
24 |
|
if (array_key_exists($class, $this->_singletons)) { |
192
|
|
|
// singleton |
193
|
2 |
|
$this->_singletons[$class] = $object; |
194
|
|
|
} |
195
|
24 |
|
unset($this->_getting[$class]); |
196
|
|
|
|
197
|
24 |
|
return $object; |
198
|
|
|
} |
199
|
|
|
|
200
|
|
|
/** |
201
|
|
|
* Registers a class definition with this container. |
202
|
|
|
* |
203
|
|
|
* For example, |
204
|
|
|
* |
205
|
|
|
* ```php |
206
|
|
|
* // register a class name as is. This can be skipped. |
207
|
|
|
* $container->set(\yii\db\Connection::class); |
208
|
|
|
* |
209
|
|
|
* // register an interface |
210
|
|
|
* // When a class depends on the interface, the corresponding class |
211
|
|
|
* // will be instantiated as the dependent object |
212
|
|
|
* $container->set(\yii\mail\MailInterface::class, \yii\swiftmailer\Mailer::class); |
213
|
|
|
* |
214
|
|
|
* // register an alias name. You can use $container->get('foo') |
215
|
|
|
* // to create an instance of Connection |
216
|
|
|
* $container->set('foo', \yii\db\Connection::class); |
217
|
|
|
* |
218
|
|
|
* // register a class with configuration. The configuration |
219
|
|
|
* // will be applied when the class is instantiated by get() |
220
|
|
|
* $container->set(\yii\db\Connection::class, [ |
221
|
|
|
* 'dsn' => 'mysql:host=127.0.0.1;dbname=demo', |
222
|
|
|
* 'username' => 'root', |
223
|
|
|
* 'password' => '', |
224
|
|
|
* 'charset' => 'utf8', |
225
|
|
|
* ]); |
226
|
|
|
* |
227
|
|
|
* // register an alias name with class configuration |
228
|
|
|
* // In this case, a "class" element is required to specify the class |
229
|
|
|
* $container->set('db', [ |
230
|
|
|
* '__class' => \yii\db\Connection::class, |
231
|
|
|
* 'dsn' => 'mysql:host=127.0.0.1;dbname=demo', |
232
|
|
|
* 'username' => 'root', |
233
|
|
|
* 'password' => '', |
234
|
|
|
* 'charset' => 'utf8', |
235
|
|
|
* ]); |
236
|
|
|
* |
237
|
|
|
* // register a PHP callable |
238
|
|
|
* // The callable will be executed when $container->get('db') is called |
239
|
|
|
* $container->set('db', function ($container, $params, $config) { |
240
|
|
|
* return new \yii\db\Connection($config); |
241
|
|
|
* }); |
242
|
|
|
* ``` |
243
|
|
|
* |
244
|
|
|
* If a class definition with the same name already exists, it will be overwritten with the new one. |
245
|
|
|
* You may use [[has()]] to check if a class definition already exists. |
246
|
|
|
* |
247
|
|
|
* @param string $class class name, interface name or alias name |
248
|
|
|
* @param mixed $definition the definition associated with `$class`. It can be one of the following: |
249
|
|
|
* |
250
|
|
|
* - a PHP callable: The callable will be executed when [[get()]] is invoked. The signature of the callable |
251
|
|
|
* should be `function ($container, $params, $config)`, where `$params` stands for the list of constructor |
252
|
|
|
* parameters, `$config` the object configuration, and `$container` the container object. The return value |
253
|
|
|
* of the callable will be returned by [[get()]] as the object instance requested. |
254
|
|
|
* - a configuration array: the array contains name-value pairs that will be used to initialize the property |
255
|
|
|
* values of the newly created object when [[get()]] is called. The `class` element stands for the |
256
|
|
|
* the class of the object to be created. If `class` is not specified, `$class` will be used as the class name. |
257
|
|
|
* - a string: a class name, an interface name or an alias name. |
258
|
|
|
* @param array $params the list of constructor parameters. The parameters will be passed to the class |
259
|
|
|
* constructor when [[get()]] is called. |
260
|
|
|
* @return $this the container itself |
261
|
|
|
*/ |
262
|
536 |
|
public function set($class, $definition = [], array $params = []) |
263
|
|
|
{ |
264
|
536 |
|
$this->_definitions[$class] = $this->normalizeDefinition($class, $definition); |
|
|
|
|
265
|
536 |
|
$this->_params[$class] = $params; |
266
|
536 |
|
unset($this->_singletons[$class]); |
267
|
536 |
|
return $this; |
268
|
|
|
} |
269
|
|
|
/** |
270
|
|
|
* Registers a class definition with this container and marks the class as a singleton class. |
271
|
|
|
* |
272
|
|
|
* This method is similar to [[set()]] except that classes registered via this method will only have one |
273
|
|
|
* instance. Each time [[get()]] is called, the same instance of the specified class will be returned. |
274
|
|
|
* |
275
|
|
|
* @param string $class class name, interface name or alias name |
276
|
|
|
* @param mixed $definition the definition associated with `$class`. See [[set()]] for more details. |
277
|
|
|
* @param array $params the list of constructor parameters. The parameters will be passed to the class |
278
|
|
|
* constructor when [[get()]] is called. |
279
|
|
|
* @return $this the container itself |
280
|
|
|
* @see set() |
281
|
|
|
*/ |
282
|
1 |
|
public function setSingleton($class, $definition = [], array $params = []) |
283
|
|
|
{ |
284
|
1 |
|
$this->_definitions[$class] = $this->normalizeDefinition($class, $definition); |
|
|
|
|
285
|
1 |
|
$this->_params[$class] = $params; |
286
|
1 |
|
$this->_singletons[$class] = null; |
287
|
1 |
|
return $this; |
288
|
|
|
} |
289
|
|
|
|
290
|
|
|
/** |
291
|
|
|
* Returns a value indicating whether the container has the definition of the specified name. |
292
|
|
|
* @param string $class class name, interface name or alias name |
293
|
|
|
* @return bool whether the container has the definition of the specified name.. |
294
|
|
|
* @see set() |
295
|
|
|
*/ |
296
|
|
|
public function has($class) |
297
|
|
|
{ |
298
|
|
|
return isset($this->_definitions[$class]); |
299
|
|
|
} |
300
|
|
|
|
301
|
|
|
/** |
302
|
|
|
* Returns a value indicating whether the given name corresponds to a registered singleton. |
303
|
|
|
* @param string $class class name, interface name or alias name |
304
|
|
|
* @param bool $checkInstance whether to check if the singleton has been instantiated. |
305
|
|
|
* @return bool whether the given name corresponds to a registered singleton. If `$checkInstance` is true, |
306
|
|
|
* the method should return a value indicating whether the singleton has been instantiated. |
307
|
|
|
*/ |
308
|
|
|
public function hasSingleton($class, $checkInstance = false) |
309
|
|
|
{ |
310
|
|
|
return $checkInstance ? isset($this->_singletons[$class]) : array_key_exists($class, $this->_singletons); |
311
|
|
|
} |
312
|
|
|
|
313
|
|
|
/** |
314
|
|
|
* Removes the definition for the specified name. |
315
|
|
|
* @param string $class class name, interface name or alias name |
316
|
|
|
*/ |
317
|
|
|
public function clear($class) |
318
|
|
|
{ |
319
|
|
|
unset($this->_definitions[$class], $this->_singletons[$class]); |
320
|
|
|
} |
321
|
|
|
|
322
|
|
|
/** |
323
|
|
|
* Normalizes the class definition. |
324
|
|
|
* @param string $class class name |
325
|
|
|
* @param string|array|callable $definition the class definition |
326
|
|
|
* @return array the normalized class definition |
327
|
|
|
* @throws InvalidConfigException if the definition is invalid. |
328
|
|
|
*/ |
329
|
537 |
|
protected function normalizeDefinition($class, $definition) |
330
|
|
|
{ |
331
|
537 |
|
if (empty($definition)) { |
332
|
1 |
|
return ['__class' => $class]; |
333
|
537 |
|
} elseif (is_string($definition)) { |
334
|
6 |
|
return ['__class' => $definition]; |
335
|
534 |
|
} elseif (is_callable($definition, true) || is_object($definition)) { |
336
|
514 |
|
return $definition; |
337
|
23 |
|
} elseif (is_array($definition)) { |
338
|
23 |
|
if (!isset($definition['__class'])) { |
339
|
|
|
if (strpos($class, '\\') !== false) { |
340
|
|
|
$definition['__class'] = $class; |
341
|
|
|
} else { |
342
|
|
|
throw new InvalidConfigException('A class definition requires a "__class" member.'); |
343
|
|
|
} |
344
|
|
|
} |
345
|
|
|
|
346
|
23 |
|
return $definition; |
347
|
|
|
} |
348
|
|
|
|
349
|
|
|
throw new InvalidConfigException("Unsupported definition type for \"$class\": " . gettype($definition)); |
350
|
|
|
} |
351
|
|
|
|
352
|
|
|
/** |
353
|
|
|
* Returns the list of the object definitions or the loaded shared objects. |
354
|
|
|
* @return array the list of the object definitions or the loaded shared objects (type or ID => definition or instance). |
355
|
|
|
*/ |
356
|
|
|
public function getDefinitions() |
357
|
|
|
{ |
358
|
|
|
return $this->_definitions; |
359
|
|
|
} |
360
|
|
|
|
361
|
|
|
/** |
362
|
|
|
* Creates an instance of the specified class. |
363
|
|
|
* This method will resolve dependencies of the specified class, instantiate them, and inject |
364
|
|
|
* them into the new instance of the specified class. |
365
|
|
|
* @param string $class the class name |
366
|
|
|
* @param array $params constructor parameters |
367
|
|
|
* @param array $config configurations to be applied to the new instance |
368
|
|
|
* @return object the newly created instance of the specified class |
369
|
|
|
* @throws NotInstantiableException If resolved to an abstract class or an interface (since 2.0.9) |
370
|
|
|
*/ |
371
|
3257 |
|
protected function build($class, $params, $config) |
372
|
|
|
{ |
373
|
|
|
/* @var $reflection ReflectionClass */ |
374
|
3257 |
|
[$reflection, $dependencies] = $this->getDependencies($class); |
|
|
|
|
375
|
|
|
|
376
|
3255 |
|
if (isset($config['__construct()'])) { |
377
|
|
|
foreach ($config['__construct()'] as $index => $param) { |
378
|
|
|
$dependencies[$index] = $param; |
|
|
|
|
379
|
|
|
} |
380
|
|
|
unset($config['__construct()']); |
381
|
|
|
} |
382
|
|
|
|
383
|
3255 |
|
foreach ($params as $index => $param) { |
384
|
397 |
|
$dependencies[$index] = $param; |
|
|
|
|
385
|
|
|
} |
386
|
|
|
|
387
|
3255 |
|
$dependencies = $this->resolveDependencies($dependencies, $reflection); |
388
|
3254 |
|
if (!$reflection->isInstantiable()) { |
389
|
1 |
|
throw new NotInstantiableException($reflection->name); |
390
|
|
|
} |
391
|
3253 |
|
if (empty($config)) { |
392
|
2135 |
|
return $reflection->newInstanceArgs($dependencies); |
393
|
|
|
} |
394
|
|
|
|
395
|
3022 |
|
$config = $this->resolveDependencies($config); |
396
|
|
|
|
397
|
3022 |
|
if (!empty($dependencies) && $reflection->implementsInterface(Configurable::class)) { |
398
|
|
|
// set $config as the last parameter (existing one will be overwritten) |
399
|
3020 |
|
$dependencies[count($dependencies) - 1] = $config; |
400
|
3020 |
|
return $reflection->newInstanceArgs($dependencies); |
401
|
|
|
} |
402
|
|
|
|
403
|
2 |
|
$object = $reflection->newInstanceArgs($dependencies); |
404
|
2 |
|
foreach ($config as $name => $value) { |
405
|
2 |
|
if (substr($name, -2) === '()') { |
406
|
1 |
|
call_user_func_array([$object, substr($name, 0, -2)], $value); |
407
|
|
|
} else { |
408
|
2 |
|
$object->$name = $value; |
409
|
|
|
} |
410
|
|
|
} |
411
|
|
|
|
412
|
2 |
|
return $object; |
413
|
|
|
} |
414
|
|
|
|
415
|
|
|
/** |
416
|
|
|
* Merges the user-specified constructor parameters with the ones registered via [[set()]]. |
417
|
|
|
* @param string $class class name, interface name or alias name |
418
|
|
|
* @param array $params the constructor parameters |
419
|
|
|
* @return array the merged parameters |
420
|
|
|
*/ |
421
|
26 |
|
protected function mergeParams($class, $params) |
422
|
|
|
{ |
423
|
26 |
|
if (empty($this->_params[$class])) { |
424
|
26 |
|
return $params; |
425
|
|
|
} elseif (empty($params)) { |
426
|
4 |
|
return $this->_params[$class]; |
427
|
|
|
} |
428
|
|
|
|
429
|
|
|
$ps = $this->_params[$class]; |
430
|
|
|
foreach ($params as $index => $value) { |
431
|
|
|
$ps[$index] = $value; |
432
|
|
|
} |
433
|
|
|
|
434
|
|
|
return $ps; |
435
|
|
|
} |
436
|
|
|
|
437
|
|
|
/** |
438
|
|
|
* Returns the dependencies of the specified class. |
439
|
|
|
* @param string $class class name, interface name or alias name |
440
|
|
|
* @return array the dependencies of the specified class. |
441
|
|
|
*/ |
442
|
3257 |
|
protected function getDependencies($class) |
443
|
|
|
{ |
444
|
3257 |
|
if (isset($this->_reflections[$class])) { |
445
|
2394 |
|
return [$this->_reflections[$class], $this->_dependencies[$class]]; |
446
|
|
|
} |
447
|
|
|
|
448
|
1523 |
|
$dependencies = []; |
449
|
1523 |
|
$reflection = new ReflectionClass($class); |
450
|
|
|
|
451
|
1521 |
|
$constructor = $reflection->getConstructor(); |
452
|
1521 |
|
if ($constructor !== null) { |
453
|
1517 |
|
foreach ($constructor->getParameters() as $param) { |
454
|
1517 |
|
if ($param->isVariadic()) { |
455
|
1 |
|
break; |
456
|
1516 |
|
} elseif ($param->isDefaultValueAvailable()) { |
457
|
1516 |
|
$dependencies[] = $param->getDefaultValue(); |
458
|
|
|
} else { |
459
|
109 |
|
$c = $param->getClass(); |
460
|
1516 |
|
$dependencies[] = Instance::of($c === null ? null : $c->getName()); |
461
|
|
|
} |
462
|
|
|
} |
463
|
|
|
} |
464
|
|
|
|
465
|
1521 |
|
$this->_reflections[$class] = $reflection; |
466
|
1521 |
|
$this->_dependencies[$class] = $dependencies; |
467
|
|
|
|
468
|
1521 |
|
return [$reflection, $dependencies]; |
469
|
|
|
} |
470
|
|
|
|
471
|
|
|
/** |
472
|
|
|
* Resolves dependencies by replacing them with the actual object instances. |
473
|
|
|
* @param array $dependencies the dependencies |
474
|
|
|
* @param ReflectionClass $reflection the class reflection associated with the dependencies |
475
|
|
|
* @return array the resolved dependencies |
476
|
|
|
* @throws InvalidConfigException if a dependency cannot be resolved or if a dependency cannot be fulfilled. |
477
|
|
|
*/ |
478
|
3255 |
|
protected function resolveDependencies($dependencies, $reflection = null) |
479
|
|
|
{ |
480
|
3255 |
|
foreach ($dependencies as $index => $dependency) { |
481
|
3252 |
|
if ($dependency instanceof Instance) { |
482
|
4 |
|
if ($dependency->id !== null) { |
483
|
4 |
|
$dependencies[$index] = $this->get($dependency->id); |
484
|
|
|
} elseif ($reflection !== null) { |
485
|
|
|
$name = $reflection->getConstructor()->getParameters()[$index]->getName(); |
486
|
|
|
$class = $reflection->getName(); |
|
|
|
|
487
|
3251 |
|
throw new InvalidConfigException("Missing required parameter \"$name\" when instantiating \"$class\"."); |
488
|
|
|
} |
489
|
|
|
} |
490
|
|
|
} |
491
|
|
|
|
492
|
3254 |
|
return $dependencies; |
493
|
|
|
} |
494
|
|
|
|
495
|
|
|
/** |
496
|
|
|
* Invoke a callback with resolving dependencies in parameters. |
497
|
|
|
* |
498
|
|
|
* This methods allows invoking a callback and let type hinted parameter names to be |
499
|
|
|
* resolved as objects of the Container. It additionally allow calling function using named parameters. |
500
|
|
|
* |
501
|
|
|
* For example, the following callback may be invoked using the Container to resolve the formatter dependency: |
502
|
|
|
* |
503
|
|
|
* ```php |
504
|
|
|
* $formatString = function($string, \yii\i18n\Formatter $formatter) { |
505
|
|
|
* // ... |
506
|
|
|
* } |
507
|
|
|
* Yii::$container->invoke($formatString, ['string' => 'Hello World!']); |
508
|
|
|
* ``` |
509
|
|
|
* |
510
|
|
|
* This will pass the string `'Hello World!'` as the first param, and a formatter instance created |
511
|
|
|
* by the DI container as the second param to the callable. |
512
|
|
|
* |
513
|
|
|
* @param callable $callback callable to be invoked. |
514
|
|
|
* @param array $params The array of parameters for the function. |
515
|
|
|
* This can be either a list of parameters, or an associative array representing named function parameters. |
516
|
|
|
* @return mixed the callback return value. |
517
|
|
|
* @throws InvalidConfigException if a dependency cannot be resolved or if a dependency cannot be fulfilled. |
518
|
|
|
* @throws NotInstantiableException If resolved to an abstract class or an interface (since 2.0.9) |
519
|
|
|
* @since 2.0.7 |
520
|
|
|
*/ |
521
|
10 |
|
public function invoke(callable $callback, $params = []) |
522
|
|
|
{ |
523
|
10 |
|
if (is_callable($callback)) { |
524
|
10 |
|
return call_user_func_array($callback, $this->resolveCallableDependencies($callback, $params)); |
525
|
|
|
} |
526
|
|
|
|
527
|
|
|
return call_user_func_array($callback, $params); |
528
|
|
|
} |
529
|
|
|
|
530
|
|
|
/** |
531
|
|
|
* Resolve dependencies for a function. |
532
|
|
|
* |
533
|
|
|
* This method can be used to implement similar functionality as provided by [[invoke()]] in other |
534
|
|
|
* components. |
535
|
|
|
* |
536
|
|
|
* @param callable $callback callable to be invoked. |
537
|
|
|
* @param array $params The array of parameters for the function, can be either numeric or associative. |
538
|
|
|
* @return array The resolved dependencies. |
539
|
|
|
* @throws InvalidConfigException if a dependency cannot be resolved or if a dependency cannot be fulfilled. |
540
|
|
|
* @throws NotInstantiableException If resolved to an abstract class or an interface (since 2.0.9) |
541
|
|
|
* @since 2.0.7 |
542
|
|
|
*/ |
543
|
11 |
|
public function resolveCallableDependencies(callable $callback, $params = []) |
544
|
|
|
{ |
545
|
11 |
|
if (is_array($callback)) { |
546
|
2 |
|
$reflection = new \ReflectionMethod($callback[0], $callback[1]); |
547
|
|
|
} else { |
548
|
11 |
|
$reflection = new \ReflectionFunction($callback); |
549
|
|
|
} |
550
|
|
|
|
551
|
11 |
|
$args = []; |
552
|
|
|
|
553
|
11 |
|
$associative = ArrayHelper::isAssociative($params); |
554
|
|
|
|
555
|
11 |
|
foreach ($reflection->getParameters() as $param) { |
556
|
6 |
|
$name = $param->getName(); |
557
|
6 |
|
if (($class = $param->getClass()) !== null) { |
558
|
4 |
|
$className = $class->getName(); |
559
|
4 |
|
if ($param->isVariadic()) { |
560
|
1 |
|
$args = array_merge($args, array_values($params)); |
561
|
1 |
|
break; |
562
|
3 |
|
} elseif ($associative && isset($params[$name]) && $params[$name] instanceof $className) { |
563
|
|
|
$args[] = $params[$name]; |
564
|
|
|
unset($params[$name]); |
565
|
3 |
|
} elseif (!$associative && isset($params[0]) && $params[0] instanceof $className) { |
566
|
1 |
|
$args[] = array_shift($params); |
567
|
3 |
|
} elseif (isset(Yii::$app) && Yii::$app->has($name) && ($obj = Yii::$app->get($name)) instanceof $className) { |
568
|
1 |
|
$args[] = $obj; |
569
|
|
|
} else { |
570
|
|
|
// If the argument is optional we catch not instantiable exceptions |
571
|
|
|
try { |
572
|
3 |
|
$args[] = $this->get($className); |
573
|
1 |
|
} catch (NotInstantiableException $e) { |
574
|
1 |
|
if ($param->isDefaultValueAvailable()) { |
575
|
1 |
|
$args[] = $param->getDefaultValue(); |
576
|
|
|
} else { |
577
|
3 |
|
throw $e; |
578
|
|
|
} |
579
|
|
|
} |
580
|
|
|
} |
581
|
4 |
|
} elseif ($associative && isset($params[$name])) { |
582
|
2 |
|
$args[] = $params[$name]; |
583
|
2 |
|
unset($params[$name]); |
584
|
4 |
|
} elseif (!$associative && count($params)) { |
585
|
3 |
|
$args[] = array_shift($params); |
586
|
3 |
|
} elseif ($param->isDefaultValueAvailable()) { |
587
|
3 |
|
$args[] = $param->getDefaultValue(); |
588
|
1 |
|
} elseif (!$param->isOptional()) { |
589
|
|
|
$funcName = $reflection->getName(); |
590
|
5 |
|
throw new InvalidConfigException("Missing required parameter \"$name\" when calling \"$funcName\"."); |
591
|
|
|
} |
592
|
|
|
} |
593
|
|
|
|
594
|
11 |
|
foreach ($params as $value) { |
595
|
|
|
$args[] = $value; |
596
|
|
|
} |
597
|
|
|
|
598
|
11 |
|
return $args; |
599
|
|
|
} |
600
|
|
|
|
601
|
|
|
/** |
602
|
|
|
* Registers class definitions within this container. |
603
|
|
|
* |
604
|
|
|
* @param array $definitions array of definitions. There are two allowed formats of array. |
605
|
|
|
* The first format: |
606
|
|
|
* - key: class name, interface name or alias name. The key will be passed to the [[set()]] method |
607
|
|
|
* as a first argument `$class`. |
608
|
|
|
* - value: the definition associated with `$class`. Possible values are described in |
609
|
|
|
* [[set()]] documentation for the `$definition` parameter. Will be passed to the [[set()]] method |
610
|
|
|
* as the second argument `$definition`. |
611
|
|
|
* |
612
|
|
|
* Example: |
613
|
|
|
* ```php |
614
|
|
|
* $container->setDefinitions([ |
615
|
|
|
* 'yii\web\Request' => 'app\components\Request', |
616
|
|
|
* 'yii\web\Response' => [ |
617
|
|
|
* '__class' => 'app\components\Response', |
618
|
|
|
* 'format' => 'json' |
619
|
|
|
* ], |
620
|
|
|
* 'foo\Bar' => function () { |
621
|
|
|
* $qux = new Qux; |
622
|
|
|
* $foo = new Foo($qux); |
623
|
|
|
* return new Bar($foo); |
624
|
|
|
* } |
625
|
|
|
* ]); |
626
|
|
|
* ``` |
627
|
|
|
* |
628
|
|
|
* The second format: |
629
|
|
|
* - key: class name, interface name or alias name. The key will be passed to the [[set()]] method |
630
|
|
|
* as a first argument `$class`. |
631
|
|
|
* - value: array of two elements. The first element will be passed the [[set()]] method as the |
632
|
|
|
* second argument `$definition`, the second one — as `$params`. |
633
|
|
|
* |
634
|
|
|
* Example: |
635
|
|
|
* ```php |
636
|
|
|
* $container->setDefinitions([ |
637
|
|
|
* 'foo\Bar' => [ |
638
|
|
|
* ['__class' => 'app\Bar'], |
639
|
|
|
* [Instance::of('baz')] |
640
|
|
|
* ] |
641
|
|
|
* ]); |
642
|
|
|
* ``` |
643
|
|
|
* |
644
|
|
|
* @see set() to know more about possible values of definitions |
645
|
|
|
* @since 2.0.11 |
646
|
|
|
*/ |
647
|
2 |
|
public function setDefinitions(array $definitions) |
648
|
|
|
{ |
649
|
2 |
|
foreach ($definitions as $class => $definition) { |
650
|
2 |
|
if (is_array($definition) && count($definition) === 2 && array_values($definition) === $definition) { |
651
|
1 |
|
$this->set($class, $definition[0], $definition[1]); |
652
|
1 |
|
continue; |
653
|
|
|
} |
654
|
|
|
|
655
|
2 |
|
$this->set($class, $definition); |
656
|
|
|
} |
657
|
2 |
|
} |
658
|
|
|
|
659
|
|
|
/** |
660
|
|
|
* Registers class definitions as singletons within this container by calling [[setSingleton()]]. |
661
|
|
|
* |
662
|
|
|
* @param array $singletons array of singleton definitions. See [[setDefinitions()]] |
663
|
|
|
* for allowed formats of array. |
664
|
|
|
* |
665
|
|
|
* @see setDefinitions() for allowed formats of $singletons parameter |
666
|
|
|
* @see setSingleton() to know more about possible values of definitions |
667
|
|
|
* @since 2.0.11 |
668
|
|
|
*/ |
669
|
1 |
|
public function setSingletons(array $singletons) |
670
|
|
|
{ |
671
|
1 |
|
foreach ($singletons as $class => $definition) { |
672
|
1 |
|
if (is_array($definition) && count($definition) === 2 && array_values($definition) === $definition) { |
673
|
1 |
|
$this->setSingleton($class, $definition[0], $definition[1]); |
674
|
1 |
|
continue; |
675
|
|
|
} |
676
|
|
|
|
677
|
1 |
|
$this->setSingleton($class, $definition); |
678
|
|
|
} |
679
|
1 |
|
} |
680
|
|
|
} |
681
|
|
|
|
It seems like the type of the argument is not accepted by the function/method which you are calling.
In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.
We suggest to add an explicit type cast like in the following example: