Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

Container.php 23KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567
  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\Object;
  37. * use yii\db\Connection;
  38. * use yii\di\Container;
  39. *
  40. * interface UserFinderInterface
  41. * {
  42. * function findUser();
  43. * }
  44. *
  45. * class UserFinder extends Object 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 Object
  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. * @property array $definitions The list of the object definitions or the loaded shared objects (type or ID =>
  90. * definition or instance). This property is read-only.
  91. *
  92. * @author Qiang Xue <qiang.xue@gmail.com>
  93. * @since 2.0
  94. */
  95. class Container extends Component
  96. {
  97. /**
  98. * @var array singleton objects indexed by their types
  99. */
  100. private $_singletons = [];
  101. /**
  102. * @var array object definitions indexed by their types
  103. */
  104. private $_definitions = [];
  105. /**
  106. * @var array constructor parameters indexed by object types
  107. */
  108. private $_params = [];
  109. /**
  110. * @var array cached ReflectionClass objects indexed by class/interface names
  111. */
  112. private $_reflections = [];
  113. /**
  114. * @var array cached dependencies indexed by class/interface names. Each class name
  115. * is associated with a list of constructor parameter types or default values.
  116. */
  117. private $_dependencies = [];
  118. /**
  119. * Returns an instance of the requested class.
  120. *
  121. * You may provide constructor parameters (`$params`) and object configurations (`$config`)
  122. * that will be used during the creation of the instance.
  123. *
  124. * If the class implements [[\yii\base\Configurable]], the `$config` parameter will be passed as the last
  125. * parameter to the class constructor; Otherwise, the configuration will be applied *after* the object is
  126. * instantiated.
  127. *
  128. * Note that if the class is declared to be singleton by calling [[setSingleton()]],
  129. * the same instance of the class will be returned each time this method is called.
  130. * In this case, the constructor parameters and object configurations will be used
  131. * only if the class is instantiated the first time.
  132. *
  133. * @param string $class the class name or an alias name (e.g. `foo`) that was previously registered via [[set()]]
  134. * or [[setSingleton()]].
  135. * @param array $params a list of constructor parameter values. The parameters should be provided in the order
  136. * they appear in the constructor declaration. If you want to skip some parameters, you should index the remaining
  137. * ones with the integers that represent their positions in the constructor parameter list.
  138. * @param array $config a list of name-value pairs that will be used to initialize the object properties.
  139. * @return object an instance of the requested class.
  140. * @throws InvalidConfigException if the class cannot be recognized or correspond to an invalid definition
  141. * @throws NotInstantiableException If resolved to an abstract class or an interface (since 2.0.9)
  142. */
  143. public function get($class, $params = [], $config = [])
  144. {
  145. if (isset($this->_singletons[$class])) {
  146. // singleton
  147. return $this->_singletons[$class];
  148. } elseif (!isset($this->_definitions[$class])) {
  149. return $this->build($class, $params, $config);
  150. }
  151. $definition = $this->_definitions[$class];
  152. if (is_callable($definition, true)) {
  153. $params = $this->resolveDependencies($this->mergeParams($class, $params));
  154. $object = call_user_func($definition, $this, $params, $config);
  155. } elseif (is_array($definition)) {
  156. $concrete = $definition['class'];
  157. unset($definition['class']);
  158. $config = array_merge($definition, $config);
  159. $params = $this->mergeParams($class, $params);
  160. if ($concrete === $class) {
  161. $object = $this->build($class, $params, $config);
  162. } else {
  163. $object = $this->get($concrete, $params, $config);
  164. }
  165. } elseif (is_object($definition)) {
  166. return $this->_singletons[$class] = $definition;
  167. } else {
  168. throw new InvalidConfigException('Unexpected object definition type: ' . gettype($definition));
  169. }
  170. if (array_key_exists($class, $this->_singletons)) {
  171. // singleton
  172. $this->_singletons[$class] = $object;
  173. }
  174. return $object;
  175. }
  176. /**
  177. * Registers a class definition with this container.
  178. *
  179. * For example,
  180. *
  181. * ```php
  182. * // register a class name as is. This can be skipped.
  183. * $container->set('yii\db\Connection');
  184. *
  185. * // register an interface
  186. * // When a class depends on the interface, the corresponding class
  187. * // will be instantiated as the dependent object
  188. * $container->set('yii\mail\MailInterface', 'yii\swiftmailer\Mailer');
  189. *
  190. * // register an alias name. You can use $container->get('foo')
  191. * // to create an instance of Connection
  192. * $container->set('foo', 'yii\db\Connection');
  193. *
  194. * // register a class with configuration. The configuration
  195. * // will be applied when the class is instantiated by get()
  196. * $container->set('yii\db\Connection', [
  197. * 'dsn' => 'mysql:host=127.0.0.1;dbname=demo',
  198. * 'username' => 'root',
  199. * 'password' => '',
  200. * 'charset' => 'utf8',
  201. * ]);
  202. *
  203. * // register an alias name with class configuration
  204. * // In this case, a "class" element is required to specify the class
  205. * $container->set('db', [
  206. * 'class' => 'yii\db\Connection',
  207. * 'dsn' => 'mysql:host=127.0.0.1;dbname=demo',
  208. * 'username' => 'root',
  209. * 'password' => '',
  210. * 'charset' => 'utf8',
  211. * ]);
  212. *
  213. * // register a PHP callable
  214. * // The callable will be executed when $container->get('db') is called
  215. * $container->set('db', function ($container, $params, $config) {
  216. * return new \yii\db\Connection($config);
  217. * });
  218. * ```
  219. *
  220. * If a class definition with the same name already exists, it will be overwritten with the new one.
  221. * You may use [[has()]] to check if a class definition already exists.
  222. *
  223. * @param string $class class name, interface name or alias name
  224. * @param mixed $definition the definition associated with `$class`. It can be one of the following:
  225. *
  226. * - a PHP callable: The callable will be executed when [[get()]] is invoked. The signature of the callable
  227. * should be `function ($container, $params, $config)`, where `$params` stands for the list of constructor
  228. * parameters, `$config` the object configuration, and `$container` the container object. The return value
  229. * of the callable will be returned by [[get()]] as the object instance requested.
  230. * - a configuration array: the array contains name-value pairs that will be used to initialize the property
  231. * values of the newly created object when [[get()]] is called. The `class` element stands for the
  232. * the class of the object to be created. If `class` is not specified, `$class` will be used as the class name.
  233. * - a string: a class name, an interface name or an alias name.
  234. * @param array $params the list of constructor parameters. The parameters will be passed to the class
  235. * constructor when [[get()]] is called.
  236. * @return $this the container itself
  237. */
  238. public function set($class, $definition = [], array $params = [])
  239. {
  240. $this->_definitions[$class] = $this->normalizeDefinition($class, $definition);
  241. $this->_params[$class] = $params;
  242. unset($this->_singletons[$class]);
  243. return $this;
  244. }
  245. /**
  246. * Registers a class definition with this container and marks the class as a singleton class.
  247. *
  248. * This method is similar to [[set()]] except that classes registered via this method will only have one
  249. * instance. Each time [[get()]] is called, the same instance of the specified class will be returned.
  250. *
  251. * @param string $class class name, interface name or alias name
  252. * @param mixed $definition the definition associated with `$class`. See [[set()]] for more details.
  253. * @param array $params the list of constructor parameters. The parameters will be passed to the class
  254. * constructor when [[get()]] is called.
  255. * @return $this the container itself
  256. * @see set()
  257. */
  258. public function setSingleton($class, $definition = [], array $params = [])
  259. {
  260. $this->_definitions[$class] = $this->normalizeDefinition($class, $definition);
  261. $this->_params[$class] = $params;
  262. $this->_singletons[$class] = null;
  263. return $this;
  264. }
  265. /**
  266. * Returns a value indicating whether the container has the definition of the specified name.
  267. * @param string $class class name, interface name or alias name
  268. * @return boolean whether the container has the definition of the specified name..
  269. * @see set()
  270. */
  271. public function has($class)
  272. {
  273. return isset($this->_definitions[$class]);
  274. }
  275. /**
  276. * Returns a value indicating whether the given name corresponds to a registered singleton.
  277. * @param string $class class name, interface name or alias name
  278. * @param boolean $checkInstance whether to check if the singleton has been instantiated.
  279. * @return boolean whether the given name corresponds to a registered singleton. If `$checkInstance` is true,
  280. * the method should return a value indicating whether the singleton has been instantiated.
  281. */
  282. public function hasSingleton($class, $checkInstance = false)
  283. {
  284. return $checkInstance ? isset($this->_singletons[$class]) : array_key_exists($class, $this->_singletons);
  285. }
  286. /**
  287. * Removes the definition for the specified name.
  288. * @param string $class class name, interface name or alias name
  289. */
  290. public function clear($class)
  291. {
  292. unset($this->_definitions[$class], $this->_singletons[$class]);
  293. }
  294. /**
  295. * Normalizes the class definition.
  296. * @param string $class class name
  297. * @param string|array|callable $definition the class definition
  298. * @return array the normalized class definition
  299. * @throws InvalidConfigException if the definition is invalid.
  300. */
  301. protected function normalizeDefinition($class, $definition)
  302. {
  303. if (empty($definition)) {
  304. return ['class' => $class];
  305. } elseif (is_string($definition)) {
  306. return ['class' => $definition];
  307. } elseif (is_callable($definition, true) || is_object($definition)) {
  308. return $definition;
  309. } elseif (is_array($definition)) {
  310. if (!isset($definition['class'])) {
  311. if (strpos($class, '\\') !== false) {
  312. $definition['class'] = $class;
  313. } else {
  314. throw new InvalidConfigException("A class definition requires a \"class\" member.");
  315. }
  316. }
  317. return $definition;
  318. } else {
  319. throw new InvalidConfigException("Unsupported definition type for \"$class\": " . gettype($definition));
  320. }
  321. }
  322. /**
  323. * Returns the list of the object definitions or the loaded shared objects.
  324. * @return array the list of the object definitions or the loaded shared objects (type or ID => definition or instance).
  325. */
  326. public function getDefinitions()
  327. {
  328. return $this->_definitions;
  329. }
  330. /**
  331. * Creates an instance of the specified class.
  332. * This method will resolve dependencies of the specified class, instantiate them, and inject
  333. * them into the new instance of the specified class.
  334. * @param string $class the class name
  335. * @param array $params constructor parameters
  336. * @param array $config configurations to be applied to the new instance
  337. * @return object the newly created instance of the specified class
  338. * @throws NotInstantiableException If resolved to an abstract class or an interface (since 2.0.9)
  339. */
  340. protected function build($class, $params, $config)
  341. {
  342. /* @var $reflection ReflectionClass */
  343. list ($reflection, $dependencies) = $this->getDependencies($class);
  344. foreach ($params as $index => $param) {
  345. $dependencies[$index] = $param;
  346. }
  347. $dependencies = $this->resolveDependencies($dependencies, $reflection);
  348. if (!$reflection->isInstantiable()) {
  349. throw new NotInstantiableException($reflection->name);
  350. }
  351. if (empty($config)) {
  352. return $reflection->newInstanceArgs($dependencies);
  353. }
  354. if (!empty($dependencies) && $reflection->implementsInterface('yii\base\Configurable')) {
  355. // set $config as the last parameter (existing one will be overwritten)
  356. $dependencies[count($dependencies) - 1] = $config;
  357. return $reflection->newInstanceArgs($dependencies);
  358. } else {
  359. $object = $reflection->newInstanceArgs($dependencies);
  360. foreach ($config as $name => $value) {
  361. $object->$name = $value;
  362. }
  363. return $object;
  364. }
  365. }
  366. /**
  367. * Merges the user-specified constructor parameters with the ones registered via [[set()]].
  368. * @param string $class class name, interface name or alias name
  369. * @param array $params the constructor parameters
  370. * @return array the merged parameters
  371. */
  372. protected function mergeParams($class, $params)
  373. {
  374. if (empty($this->_params[$class])) {
  375. return $params;
  376. } elseif (empty($params)) {
  377. return $this->_params[$class];
  378. } else {
  379. $ps = $this->_params[$class];
  380. foreach ($params as $index => $value) {
  381. $ps[$index] = $value;
  382. }
  383. return $ps;
  384. }
  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. */
  391. protected function getDependencies($class)
  392. {
  393. if (isset($this->_reflections[$class])) {
  394. return [$this->_reflections[$class], $this->_dependencies[$class]];
  395. }
  396. $dependencies = [];
  397. $reflection = new ReflectionClass($class);
  398. $constructor = $reflection->getConstructor();
  399. if ($constructor !== null) {
  400. foreach ($constructor->getParameters() as $param) {
  401. if ($param->isDefaultValueAvailable()) {
  402. $dependencies[] = $param->getDefaultValue();
  403. } else {
  404. $c = $param->getClass();
  405. $dependencies[] = Instance::of($c === null ? null : $c->getName());
  406. }
  407. }
  408. }
  409. $this->_reflections[$class] = $reflection;
  410. $this->_dependencies[$class] = $dependencies;
  411. return [$reflection, $dependencies];
  412. }
  413. /**
  414. * Resolves dependencies by replacing them with the actual object instances.
  415. * @param array $dependencies the dependencies
  416. * @param ReflectionClass $reflection the class reflection associated with the dependencies
  417. * @return array the resolved dependencies
  418. * @throws InvalidConfigException if a dependency cannot be resolved or if a dependency cannot be fulfilled.
  419. */
  420. protected function resolveDependencies($dependencies, $reflection = null)
  421. {
  422. foreach ($dependencies as $index => $dependency) {
  423. if ($dependency instanceof Instance) {
  424. if ($dependency->id !== null) {
  425. $dependencies[$index] = $this->get($dependency->id);
  426. } elseif ($reflection !== null) {
  427. $name = $reflection->getConstructor()->getParameters()[$index]->getName();
  428. $class = $reflection->getName();
  429. throw new InvalidConfigException("Missing required parameter \"$name\" when instantiating \"$class\".");
  430. }
  431. }
  432. }
  433. return $dependencies;
  434. }
  435. /**
  436. * Invoke a callback with resolving dependencies in parameters.
  437. *
  438. * This methods allows invoking a callback and let type hinted parameter names to be
  439. * resolved as objects of the Container. It additionally allow calling function using named parameters.
  440. *
  441. * For example, the following callback may be invoked using the Container to resolve the formatter dependency:
  442. *
  443. * ```php
  444. * $formatString = function($string, \yii\i18n\Formatter $formatter) {
  445. * // ...
  446. * }
  447. * Yii::$container->invoke($formatString, ['string' => 'Hello World!']);
  448. * ```
  449. *
  450. * This will pass the string `'Hello World!'` as the first param, and a formatter instance created
  451. * by the DI container as the second param to the callable.
  452. *
  453. * @param callable $callback callable to be invoked.
  454. * @param array $params The array of parameters for the function.
  455. * This can be either a list of parameters, or an associative array representing named function parameters.
  456. * @return mixed the callback return value.
  457. * @throws InvalidConfigException if a dependency cannot be resolved or if a dependency cannot be fulfilled.
  458. * @throws NotInstantiableException If resolved to an abstract class or an interface (since 2.0.9)
  459. * @since 2.0.7
  460. */
  461. public function invoke(callable $callback, $params = [])
  462. {
  463. if (is_callable($callback)) {
  464. return call_user_func_array($callback, $this->resolveCallableDependencies($callback, $params));
  465. } else {
  466. return call_user_func_array($callback, $params);
  467. }
  468. }
  469. /**
  470. * Resolve dependencies for a function.
  471. *
  472. * This method can be used to implement similar functionality as provided by [[invoke()]] in other
  473. * components.
  474. *
  475. * @param callable $callback callable to be invoked.
  476. * @param array $params The array of parameters for the function, can be either numeric or associative.
  477. * @return array The resolved dependencies.
  478. * @throws InvalidConfigException if a dependency cannot be resolved or if a dependency cannot be fulfilled.
  479. * @throws NotInstantiableException If resolved to an abstract class or an interface (since 2.0.9)
  480. * @since 2.0.7
  481. */
  482. public function resolveCallableDependencies(callable $callback, $params = [])
  483. {
  484. if (is_array($callback)) {
  485. $reflection = new \ReflectionMethod($callback[0], $callback[1]);
  486. } else {
  487. $reflection = new \ReflectionFunction($callback);
  488. }
  489. $args = [];
  490. $associative = ArrayHelper::isAssociative($params);
  491. foreach ($reflection->getParameters() as $param) {
  492. $name = $param->getName();
  493. if (($class = $param->getClass()) !== null) {
  494. $className = $class->getName();
  495. if ($associative && isset($params[$name]) && $params[$name] instanceof $className) {
  496. $args[] = $params[$name];
  497. unset($params[$name]);
  498. } elseif (!$associative && isset($params[0]) && $params[0] instanceof $className) {
  499. $args[] = array_shift($params);
  500. } elseif (isset(Yii::$app) && Yii::$app->has($name) && ($obj = Yii::$app->get($name)) instanceof $className) {
  501. $args[] = $obj;
  502. } else {
  503. // If the argument is optional we catch not instantiable exceptions
  504. try {
  505. $args[] = $this->get($className);
  506. } catch (NotInstantiableException $e) {
  507. if ($param->isDefaultValueAvailable()) {
  508. $args[] = $param->getDefaultValue();
  509. } else {
  510. throw $e;
  511. }
  512. }
  513. }
  514. } elseif ($associative && isset($params[$name])) {
  515. $args[] = $params[$name];
  516. unset($params[$name]);
  517. } elseif (!$associative && count($params)) {
  518. $args[] = array_shift($params);
  519. } elseif ($param->isDefaultValueAvailable()) {
  520. $args[] = $param->getDefaultValue();
  521. } elseif (!$param->isOptional()) {
  522. $funcName = $reflection->getName();
  523. throw new InvalidConfigException("Missing required parameter \"$name\" when calling \"$funcName\".");
  524. }
  525. }
  526. foreach ($params as $value) {
  527. $args[] = $value;
  528. }
  529. return $args;
  530. }
  531. }