Container.php 31 KB

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