Container.php 27 KB

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