Container.php 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664
  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 $class the class 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 (isset($this->_singletons[$class])) {
  148. // singleton
  149. return $this->_singletons[$class];
  150. } elseif (!isset($this->_definitions[$class])) {
  151. return $this->build($class, $params, $config);
  152. }
  153. $definition = $this->_definitions[$class];
  154. if (is_callable($definition, true)) {
  155. $params = $this->resolveDependencies($this->mergeParams($class, $params));
  156. $object = call_user_func($definition, $this, $params, $config);
  157. } elseif (is_array($definition)) {
  158. $concrete = $definition['class'];
  159. unset($definition['class']);
  160. $config = array_merge($definition, $config);
  161. $params = $this->mergeParams($class, $params);
  162. if ($concrete === $class) {
  163. $object = $this->build($class, $params, $config);
  164. } else {
  165. $object = $this->get($concrete, $params, $config);
  166. }
  167. } elseif (is_object($definition)) {
  168. return $this->_singletons[$class] = $definition;
  169. } else {
  170. throw new InvalidConfigException('Unexpected object definition type: ' . gettype($definition));
  171. }
  172. if (array_key_exists($class, $this->_singletons)) {
  173. // singleton
  174. $this->_singletons[$class] = $object;
  175. }
  176. return $object;
  177. }
  178. /**
  179. * Registers a class definition with this container.
  180. *
  181. * For example,
  182. *
  183. * ```php
  184. * // register a class name as is. This can be skipped.
  185. * $container->set('yii\db\Connection');
  186. *
  187. * // register an interface
  188. * // When a class depends on the interface, the corresponding class
  189. * // will be instantiated as the dependent object
  190. * $container->set('yii\mail\MailInterface', 'yii\swiftmailer\Mailer');
  191. *
  192. * // register an alias name. You can use $container->get('foo')
  193. * // to create an instance of Connection
  194. * $container->set('foo', 'yii\db\Connection');
  195. *
  196. * // register a class with configuration. The configuration
  197. * // will be applied when the class is instantiated by get()
  198. * $container->set('yii\db\Connection', [
  199. * 'dsn' => 'mysql:host=127.0.0.1;dbname=demo',
  200. * 'username' => 'root',
  201. * 'password' => '',
  202. * 'charset' => 'utf8',
  203. * ]);
  204. *
  205. * // register an alias name with class configuration
  206. * // In this case, a "class" element is required to specify the class
  207. * $container->set('db', [
  208. * 'class' => 'yii\db\Connection',
  209. * 'dsn' => 'mysql:host=127.0.0.1;dbname=demo',
  210. * 'username' => 'root',
  211. * 'password' => '',
  212. * 'charset' => 'utf8',
  213. * ]);
  214. *
  215. * // register a PHP callable
  216. * // The callable will be executed when $container->get('db') is called
  217. * $container->set('db', function ($container, $params, $config) {
  218. * return new \yii\db\Connection($config);
  219. * });
  220. * ```
  221. *
  222. * If a class definition with the same name already exists, it will be overwritten with the new one.
  223. * You may use [[has()]] to check if a class definition already exists.
  224. *
  225. * @param string $class class name, interface name or alias name
  226. * @param mixed $definition the definition associated with `$class`. It can be one of the following:
  227. *
  228. * - a PHP callable: The callable will be executed when [[get()]] is invoked. The signature of the callable
  229. * should be `function ($container, $params, $config)`, where `$params` stands for the list of constructor
  230. * parameters, `$config` the object configuration, and `$container` the container object. The return value
  231. * of the callable will be returned by [[get()]] as the object instance requested.
  232. * - a configuration array: the array contains name-value pairs that will be used to initialize the property
  233. * values of the newly created object when [[get()]] is called. The `class` element stands for the
  234. * the class of the object to be created. If `class` is not specified, `$class` will be used as the class name.
  235. * - a string: a class name, an interface name or an alias name.
  236. * @param array $params the list of constructor parameters. The parameters will be passed to the class
  237. * constructor when [[get()]] is called.
  238. * @return $this the container itself
  239. */
  240. public function set($class, $definition = [], array $params = [])
  241. {
  242. $this->_definitions[$class] = $this->normalizeDefinition($class, $definition);
  243. $this->_params[$class] = $params;
  244. unset($this->_singletons[$class]);
  245. return $this;
  246. }
  247. /**
  248. * Registers a class definition with this container and marks the class as a singleton class.
  249. *
  250. * This method is similar to [[set()]] except that classes registered via this method will only have one
  251. * instance. Each time [[get()]] is called, the same instance of the specified class will be returned.
  252. *
  253. * @param string $class class name, interface name or alias name
  254. * @param mixed $definition the definition associated with `$class`. See [[set()]] for more details.
  255. * @param array $params the list of constructor parameters. The parameters will be passed to the class
  256. * constructor when [[get()]] is called.
  257. * @return $this the container itself
  258. * @see set()
  259. */
  260. public function setSingleton($class, $definition = [], array $params = [])
  261. {
  262. $this->_definitions[$class] = $this->normalizeDefinition($class, $definition);
  263. $this->_params[$class] = $params;
  264. $this->_singletons[$class] = null;
  265. return $this;
  266. }
  267. /**
  268. * Returns a value indicating whether the container has the definition of the specified name.
  269. * @param string $class class name, interface name or alias name
  270. * @return bool whether the container has the definition of the specified name..
  271. * @see set()
  272. */
  273. public function has($class)
  274. {
  275. return isset($this->_definitions[$class]);
  276. }
  277. /**
  278. * Returns a value indicating whether the given name corresponds to a registered singleton.
  279. * @param string $class class name, interface name or alias name
  280. * @param bool $checkInstance whether to check if the singleton has been instantiated.
  281. * @return bool whether the given name corresponds to a registered singleton. If `$checkInstance` is true,
  282. * the method should return a value indicating whether the singleton has been instantiated.
  283. */
  284. public function hasSingleton($class, $checkInstance = false)
  285. {
  286. return $checkInstance ? isset($this->_singletons[$class]) : array_key_exists($class, $this->_singletons);
  287. }
  288. /**
  289. * Removes the definition for the specified name.
  290. * @param string $class class name, interface name or alias name
  291. */
  292. public function clear($class)
  293. {
  294. unset($this->_definitions[$class], $this->_singletons[$class]);
  295. }
  296. /**
  297. * Normalizes the class definition.
  298. * @param string $class class name
  299. * @param string|array|callable $definition the class definition
  300. * @return array the normalized class definition
  301. * @throws InvalidConfigException if the definition is invalid.
  302. */
  303. protected function normalizeDefinition($class, $definition)
  304. {
  305. if (empty($definition)) {
  306. return ['class' => $class];
  307. } elseif (is_string($definition)) {
  308. return ['class' => $definition];
  309. } elseif (is_callable($definition, true) || is_object($definition)) {
  310. return $definition;
  311. } elseif (is_array($definition)) {
  312. if (!isset($definition['class'])) {
  313. if (strpos($class, '\\') !== false) {
  314. $definition['class'] = $class;
  315. } else {
  316. throw new InvalidConfigException('A class definition requires a "class" member.');
  317. }
  318. }
  319. return $definition;
  320. }
  321. throw new InvalidConfigException("Unsupported definition type for \"$class\": " . gettype($definition));
  322. }
  323. /**
  324. * Returns the list of the object definitions or the loaded shared objects.
  325. * @return array the list of the object definitions or the loaded shared objects (type or ID => definition or instance).
  326. */
  327. public function getDefinitions()
  328. {
  329. return $this->_definitions;
  330. }
  331. /**
  332. * Creates an instance of the specified class.
  333. * This method will resolve dependencies of the specified class, instantiate them, and inject
  334. * them into the new instance of the specified class.
  335. * @param string $class the class name
  336. * @param array $params constructor parameters
  337. * @param array $config configurations to be applied to the new instance
  338. * @return object the newly created instance of the specified class
  339. * @throws NotInstantiableException If resolved to an abstract class or an interface (since 2.0.9)
  340. */
  341. protected function build($class, $params, $config)
  342. {
  343. /* @var $reflection ReflectionClass */
  344. list($reflection, $dependencies) = $this->getDependencies($class);
  345. foreach ($params as $index => $param) {
  346. $dependencies[$index] = $param;
  347. }
  348. $dependencies = $this->resolveDependencies($dependencies, $reflection);
  349. if (!$reflection->isInstantiable()) {
  350. throw new NotInstantiableException($reflection->name);
  351. }
  352. if (empty($config)) {
  353. return $reflection->newInstanceArgs($dependencies);
  354. }
  355. $config = $this->resolveDependencies($config);
  356. if (!empty($dependencies) && $reflection->implementsInterface('yii\base\Configurable')) {
  357. // set $config as the last parameter (existing one will be overwritten)
  358. $dependencies[count($dependencies) - 1] = $config;
  359. return $reflection->newInstanceArgs($dependencies);
  360. }
  361. $object = $reflection->newInstanceArgs($dependencies);
  362. foreach ($config as $name => $value) {
  363. $object->$name = $value;
  364. }
  365. return $object;
  366. }
  367. /**
  368. * Merges the user-specified constructor parameters with the ones registered via [[set()]].
  369. * @param string $class class name, interface name or alias name
  370. * @param array $params the constructor parameters
  371. * @return array the merged parameters
  372. */
  373. protected function mergeParams($class, $params)
  374. {
  375. if (empty($this->_params[$class])) {
  376. return $params;
  377. } elseif (empty($params)) {
  378. return $this->_params[$class];
  379. }
  380. $ps = $this->_params[$class];
  381. foreach ($params as $index => $value) {
  382. $ps[$index] = $value;
  383. }
  384. return $ps;
  385. }
  386. /**
  387. * Returns the dependencies of the specified class.
  388. * @param string $class class name, interface name or alias name
  389. * @return array the dependencies of the specified class.
  390. * @throws InvalidConfigException if a dependency cannot be resolved or if a dependency cannot be fulfilled.
  391. */
  392. protected function getDependencies($class)
  393. {
  394. if (isset($this->_reflections[$class])) {
  395. return [$this->_reflections[$class], $this->_dependencies[$class]];
  396. }
  397. $dependencies = [];
  398. try {
  399. $reflection = new ReflectionClass($class);
  400. } catch (\ReflectionException $e) {
  401. throw new InvalidConfigException('Failed to instantiate component or class "' . $class . '".', 0, $e);
  402. }
  403. $constructor = $reflection->getConstructor();
  404. if ($constructor !== null) {
  405. foreach ($constructor->getParameters() as $param) {
  406. if (version_compare(PHP_VERSION, '5.6.0', '>=') && $param->isVariadic()) {
  407. break;
  408. } elseif ($param->isDefaultValueAvailable()) {
  409. $dependencies[] = $param->getDefaultValue();
  410. } else {
  411. $c = $param->getClass();
  412. $dependencies[] = Instance::of($c === null ? null : $c->getName());
  413. }
  414. }
  415. }
  416. $this->_reflections[$class] = $reflection;
  417. $this->_dependencies[$class] = $dependencies;
  418. return [$reflection, $dependencies];
  419. }
  420. /**
  421. * Resolves dependencies by replacing them with the actual object instances.
  422. * @param array $dependencies the dependencies
  423. * @param ReflectionClass $reflection the class reflection associated with the dependencies
  424. * @return array the resolved dependencies
  425. * @throws InvalidConfigException if a dependency cannot be resolved or if a dependency cannot be fulfilled.
  426. */
  427. protected function resolveDependencies($dependencies, $reflection = null)
  428. {
  429. foreach ($dependencies as $index => $dependency) {
  430. if ($dependency instanceof Instance) {
  431. if ($dependency->id !== null) {
  432. $dependencies[$index] = $this->get($dependency->id);
  433. } elseif ($reflection !== null) {
  434. $name = $reflection->getConstructor()->getParameters()[$index]->getName();
  435. $class = $reflection->getName();
  436. throw new InvalidConfigException("Missing required parameter \"$name\" when instantiating \"$class\".");
  437. }
  438. }
  439. }
  440. return $dependencies;
  441. }
  442. /**
  443. * Invoke a callback with resolving dependencies in parameters.
  444. *
  445. * This methods allows invoking a callback and let type hinted parameter names to be
  446. * resolved as objects of the Container. It additionally allow calling function using named parameters.
  447. *
  448. * For example, the following callback may be invoked using the Container to resolve the formatter dependency:
  449. *
  450. * ```php
  451. * $formatString = function($string, \yii\i18n\Formatter $formatter) {
  452. * // ...
  453. * }
  454. * Yii::$container->invoke($formatString, ['string' => 'Hello World!']);
  455. * ```
  456. *
  457. * This will pass the string `'Hello World!'` as the first param, and a formatter instance created
  458. * by the DI container as the second param to the callable.
  459. *
  460. * @param callable $callback callable to be invoked.
  461. * @param array $params The array of parameters for the function.
  462. * This can be either a list of parameters, or an associative array representing named function parameters.
  463. * @return mixed the callback return value.
  464. * @throws InvalidConfigException if a dependency cannot be resolved or if a dependency cannot be fulfilled.
  465. * @throws NotInstantiableException If resolved to an abstract class or an interface (since 2.0.9)
  466. * @since 2.0.7
  467. */
  468. public function invoke(callable $callback, $params = [])
  469. {
  470. return call_user_func_array($callback, $this->resolveCallableDependencies($callback, $params));
  471. }
  472. /**
  473. * Resolve dependencies for a function.
  474. *
  475. * This method can be used to implement similar functionality as provided by [[invoke()]] in other
  476. * components.
  477. *
  478. * @param callable $callback callable to be invoked.
  479. * @param array $params The array of parameters for the function, can be either numeric or associative.
  480. * @return array The resolved dependencies.
  481. * @throws InvalidConfigException if a dependency cannot be resolved or if a dependency cannot be fulfilled.
  482. * @throws NotInstantiableException If resolved to an abstract class or an interface (since 2.0.9)
  483. * @since 2.0.7
  484. */
  485. public function resolveCallableDependencies(callable $callback, $params = [])
  486. {
  487. if (is_array($callback)) {
  488. $reflection = new \ReflectionMethod($callback[0], $callback[1]);
  489. } elseif (is_object($callback) && !$callback instanceof \Closure) {
  490. $reflection = new \ReflectionMethod($callback, '__invoke');
  491. } else {
  492. $reflection = new \ReflectionFunction($callback);
  493. }
  494. $args = [];
  495. $associative = ArrayHelper::isAssociative($params);
  496. foreach ($reflection->getParameters() as $param) {
  497. $name = $param->getName();
  498. if (($class = $param->getClass()) !== null) {
  499. $className = $class->getName();
  500. if (version_compare(PHP_VERSION, '5.6.0', '>=') && $param->isVariadic()) {
  501. $args = array_merge($args, array_values($params));
  502. break;
  503. } elseif ($associative && isset($params[$name]) && $params[$name] instanceof $className) {
  504. $args[] = $params[$name];
  505. unset($params[$name]);
  506. } elseif (!$associative && isset($params[0]) && $params[0] instanceof $className) {
  507. $args[] = array_shift($params);
  508. } elseif (isset(Yii::$app) && Yii::$app->has($name) && ($obj = Yii::$app->get($name)) instanceof $className) {
  509. $args[] = $obj;
  510. } else {
  511. // If the argument is optional we catch not instantiable exceptions
  512. try {
  513. $args[] = $this->get($className);
  514. } catch (NotInstantiableException $e) {
  515. if ($param->isDefaultValueAvailable()) {
  516. $args[] = $param->getDefaultValue();
  517. } else {
  518. throw $e;
  519. }
  520. }
  521. }
  522. } elseif ($associative && isset($params[$name])) {
  523. $args[] = $params[$name];
  524. unset($params[$name]);
  525. } elseif (!$associative && count($params)) {
  526. $args[] = array_shift($params);
  527. } elseif ($param->isDefaultValueAvailable()) {
  528. $args[] = $param->getDefaultValue();
  529. } elseif (!$param->isOptional()) {
  530. $funcName = $reflection->getName();
  531. throw new InvalidConfigException("Missing required parameter \"$name\" when calling \"$funcName\".");
  532. }
  533. }
  534. foreach ($params as $value) {
  535. $args[] = $value;
  536. }
  537. return $args;
  538. }
  539. /**
  540. * Registers class definitions within this container.
  541. *
  542. * @param array $definitions array of definitions. There are two allowed formats of array.
  543. * The first format:
  544. * - key: class name, interface name or alias name. The key will be passed to the [[set()]] method
  545. * as a first argument `$class`.
  546. * - value: the definition associated with `$class`. Possible values are described in
  547. * [[set()]] documentation for the `$definition` parameter. Will be passed to the [[set()]] method
  548. * as the second argument `$definition`.
  549. *
  550. * Example:
  551. * ```php
  552. * $container->setDefinitions([
  553. * 'yii\web\Request' => 'app\components\Request',
  554. * 'yii\web\Response' => [
  555. * 'class' => 'app\components\Response',
  556. * 'format' => 'json'
  557. * ],
  558. * 'foo\Bar' => function () {
  559. * $qux = new Qux;
  560. * $foo = new Foo($qux);
  561. * return new Bar($foo);
  562. * }
  563. * ]);
  564. * ```
  565. *
  566. * The second format:
  567. * - key: class name, interface name or alias name. The key will be passed to the [[set()]] method
  568. * as a first argument `$class`.
  569. * - value: array of two elements. The first element will be passed the [[set()]] method as the
  570. * second argument `$definition`, the second one — as `$params`.
  571. *
  572. * Example:
  573. * ```php
  574. * $container->setDefinitions([
  575. * 'foo\Bar' => [
  576. * ['class' => 'app\Bar'],
  577. * [Instance::of('baz')]
  578. * ]
  579. * ]);
  580. * ```
  581. *
  582. * @see set() to know more about possible values of definitions
  583. * @since 2.0.11
  584. */
  585. public function setDefinitions(array $definitions)
  586. {
  587. foreach ($definitions as $class => $definition) {
  588. if (is_array($definition) && count($definition) === 2 && array_values($definition) === $definition) {
  589. $this->set($class, $definition[0], $definition[1]);
  590. continue;
  591. }
  592. $this->set($class, $definition);
  593. }
  594. }
  595. /**
  596. * Registers class definitions as singletons within this container by calling [[setSingleton()]].
  597. *
  598. * @param array $singletons array of singleton definitions. See [[setDefinitions()]]
  599. * for allowed formats of array.
  600. *
  601. * @see setDefinitions() for allowed formats of $singletons parameter
  602. * @see setSingleton() to know more about possible values of definitions
  603. * @since 2.0.11
  604. */
  605. public function setSingletons(array $singletons)
  606. {
  607. foreach ($singletons as $class => $definition) {
  608. if (is_array($definition) && count($definition) === 2 && array_values($definition) === $definition) {
  609. $this->setSingleton($class, $definition[0], $definition[1]);
  610. continue;
  611. }
  612. $this->setSingleton($class, $definition);
  613. }
  614. }
  615. }