Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

458 lines
18KB

  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\base\Component;
  10. use yii\base\InvalidConfigException;
  11. /**
  12. * Container implements a [dependency injection](http://en.wikipedia.org/wiki/Dependency_injection) container.
  13. *
  14. * A dependency injection (DI) container is an object that knows how to instantiate and configure objects and
  15. * all their dependent objects. For more information about DI, please refer to
  16. * [Martin Fowler's article](http://martinfowler.com/articles/injection.html).
  17. *
  18. * Container supports constructor injection as well as property injection.
  19. *
  20. * To use Container, you first need to set up the class dependencies by calling [[set()]].
  21. * You then call [[get()]] to create a new class object. Container will automatically instantiate
  22. * dependent objects, inject them into the object being created, configure and finally return the newly created object.
  23. *
  24. * By default, [[\Yii::$container]] refers to a Container instance which is used by [[\Yii::createObject()]]
  25. * to create new object instances. You may use this method to replace the `new` operator
  26. * when creating a new object, which gives you the benefit of automatic dependency resolution and default
  27. * property configuration.
  28. *
  29. * Below is an example of using Container:
  30. *
  31. * ```php
  32. * namespace app\models;
  33. *
  34. * use yii\base\Object;
  35. * use yii\db\Connection;
  36. * use yii\di\Container;
  37. *
  38. * interface UserFinderInterface
  39. * {
  40. * function findUser();
  41. * }
  42. *
  43. * class UserFinder extends Object implements UserFinderInterface
  44. * {
  45. * public $db;
  46. *
  47. * public function __construct(Connection $db, $config = [])
  48. * {
  49. * $this->db = $db;
  50. * parent::__construct($config);
  51. * }
  52. *
  53. * public function findUser()
  54. * {
  55. * }
  56. * }
  57. *
  58. * class UserLister extends Object
  59. * {
  60. * public $finder;
  61. *
  62. * public function __construct(UserFinderInterface $finder, $config = [])
  63. * {
  64. * $this->finder = $finder;
  65. * parent::__construct($config);
  66. * }
  67. * }
  68. *
  69. * $container = new Container;
  70. * $container->set('yii\db\Connection', [
  71. * 'dsn' => '...',
  72. * ]);
  73. * $container->set('app\models\UserFinderInterface', [
  74. * 'class' => 'app\models\UserFinder',
  75. * ]);
  76. * $container->set('userLister', 'app\models\UserLister');
  77. *
  78. * $lister = $container->get('userLister');
  79. *
  80. * // which is equivalent to:
  81. *
  82. * $db = new \yii\db\Connection(['dsn' => '...']);
  83. * $finder = new UserFinder($db);
  84. * $lister = new UserLister($finder);
  85. * ```
  86. *
  87. * @property array $definitions The list of the object definitions or the loaded shared objects (type or ID =>
  88. * definition or instance). This property is read-only.
  89. *
  90. * @author Qiang Xue <qiang.xue@gmail.com>
  91. * @since 2.0
  92. */
  93. class Container extends Component
  94. {
  95. /**
  96. * @var array singleton objects indexed by their types
  97. */
  98. private $_singletons = [];
  99. /**
  100. * @var array object definitions indexed by their types
  101. */
  102. private $_definitions = [];
  103. /**
  104. * @var array constructor parameters indexed by object types
  105. */
  106. private $_params = [];
  107. /**
  108. * @var array cached ReflectionClass objects indexed by class/interface names
  109. */
  110. private $_reflections = [];
  111. /**
  112. * @var array cached dependencies indexed by class/interface names. Each class name
  113. * is associated with a list of constructor parameter types or default values.
  114. */
  115. private $_dependencies = [];
  116. /**
  117. * Returns an instance of the requested class.
  118. *
  119. * You may provide constructor parameters (`$params`) and object configurations (`$config`)
  120. * that will be used during the creation of the instance.
  121. *
  122. * If the class implements [[\yii\base\Configurable]], the `$config` parameter will be passed as the last
  123. * parameter to the class constructor; Otherwise, the configuration will be applied *after* the object is
  124. * instantiated.
  125. *
  126. * Note that if the class is declared to be singleton by calling [[setSingleton()]],
  127. * the same instance of the class will be returned each time this method is called.
  128. * In this case, the constructor parameters and object configurations will be used
  129. * only if the class is instantiated the first time.
  130. *
  131. * @param string $class the class name or an alias name (e.g. `foo`) that was previously registered via [[set()]]
  132. * or [[setSingleton()]].
  133. * @param array $params a list of constructor parameter values. The parameters should be provided in the order
  134. * they appear in the constructor declaration. If you want to skip some parameters, you should index the remaining
  135. * ones with the integers that represent their positions in the constructor parameter list.
  136. * @param array $config a list of name-value pairs that will be used to initialize the object properties.
  137. * @return object an instance of the requested class.
  138. * @throws InvalidConfigException if the class cannot be recognized or correspond to an invalid definition
  139. */
  140. public function get($class, $params = [], $config = [])
  141. {
  142. if (isset($this->_singletons[$class])) {
  143. // singleton
  144. return $this->_singletons[$class];
  145. } elseif (!isset($this->_definitions[$class])) {
  146. return $this->build($class, $params, $config);
  147. }
  148. $definition = $this->_definitions[$class];
  149. if (is_callable($definition, true)) {
  150. $params = $this->resolveDependencies($this->mergeParams($class, $params));
  151. $object = call_user_func($definition, $this, $params, $config);
  152. } elseif (is_array($definition)) {
  153. $concrete = $definition['class'];
  154. unset($definition['class']);
  155. $config = array_merge($definition, $config);
  156. $params = $this->mergeParams($class, $params);
  157. if ($concrete === $class) {
  158. $object = $this->build($class, $params, $config);
  159. } else {
  160. $object = $this->get($concrete, $params, $config);
  161. }
  162. } elseif (is_object($definition)) {
  163. return $this->_singletons[$class] = $definition;
  164. } else {
  165. throw new InvalidConfigException("Unexpected object definition type: " . gettype($definition));
  166. }
  167. if (array_key_exists($class, $this->_singletons)) {
  168. // singleton
  169. $this->_singletons[$class] = $object;
  170. }
  171. return $object;
  172. }
  173. /**
  174. * Registers a class definition with this container.
  175. *
  176. * For example,
  177. *
  178. * ```php
  179. * // register a class name as is. This can be skipped.
  180. * $container->set('yii\db\Connection');
  181. *
  182. * // register an interface
  183. * // When a class depends on the interface, the corresponding class
  184. * // will be instantiated as the dependent object
  185. * $container->set('yii\mail\MailInterface', 'yii\swiftmailer\Mailer');
  186. *
  187. * // register an alias name. You can use $container->get('foo')
  188. * // to create an instance of Connection
  189. * $container->set('foo', 'yii\db\Connection');
  190. *
  191. * // register a class with configuration. The configuration
  192. * // will be applied when the class is instantiated by get()
  193. * $container->set('yii\db\Connection', [
  194. * 'dsn' => 'mysql:host=127.0.0.1;dbname=demo',
  195. * 'username' => 'root',
  196. * 'password' => '',
  197. * 'charset' => 'utf8',
  198. * ]);
  199. *
  200. * // register an alias name with class configuration
  201. * // In this case, a "class" element is required to specify the class
  202. * $container->set('db', [
  203. * 'class' => 'yii\db\Connection',
  204. * 'dsn' => 'mysql:host=127.0.0.1;dbname=demo',
  205. * 'username' => 'root',
  206. * 'password' => '',
  207. * 'charset' => 'utf8',
  208. * ]);
  209. *
  210. * // register a PHP callable
  211. * // The callable will be executed when $container->get('db') is called
  212. * $container->set('db', function ($container, $params, $config) {
  213. * return new \yii\db\Connection($config);
  214. * });
  215. * ```
  216. *
  217. * If a class definition with the same name already exists, it will be overwritten with the new one.
  218. * You may use [[has()]] to check if a class definition already exists.
  219. *
  220. * @param string $class class name, interface name or alias name
  221. * @param mixed $definition the definition associated with `$class`. It can be one of the followings:
  222. *
  223. * - a PHP callable: The callable will be executed when [[get()]] is invoked. The signature of the callable
  224. * should be `function ($container, $params, $config)`, where `$params` stands for the list of constructor
  225. * parameters, `$config` the object configuration, and `$container` the container object. The return value
  226. * of the callable will be returned by [[get()]] as the object instance requested.
  227. * - a configuration array: the array contains name-value pairs that will be used to initialize the property
  228. * values of the newly created object when [[get()]] is called. The `class` element stands for the
  229. * the class of the object to be created. If `class` is not specified, `$class` will be used as the class name.
  230. * - a string: a class name, an interface name or an alias name.
  231. * @param array $params the list of constructor parameters. The parameters will be passed to the class
  232. * constructor when [[get()]] is called.
  233. * @return static the container itself
  234. */
  235. public function set($class, $definition = [], array $params = [])
  236. {
  237. $this->_definitions[$class] = $this->normalizeDefinition($class, $definition);
  238. $this->_params[$class] = $params;
  239. unset($this->_singletons[$class]);
  240. return $this;
  241. }
  242. /**
  243. * Registers a class definition with this container and marks the class as a singleton class.
  244. *
  245. * This method is similar to [[set()]] except that classes registered via this method will only have one
  246. * instance. Each time [[get()]] is called, the same instance of the specified class will be returned.
  247. *
  248. * @param string $class class name, interface name or alias name
  249. * @param mixed $definition the definition associated with `$class`. See [[set()]] for more details.
  250. * @param array $params the list of constructor parameters. The parameters will be passed to the class
  251. * constructor when [[get()]] is called.
  252. * @return static the container itself
  253. * @see set()
  254. */
  255. public function setSingleton($class, $definition = [], array $params = [])
  256. {
  257. $this->_definitions[$class] = $this->normalizeDefinition($class, $definition);
  258. $this->_params[$class] = $params;
  259. $this->_singletons[$class] = null;
  260. return $this;
  261. }
  262. /**
  263. * Returns a value indicating whether the container has the definition of the specified name.
  264. * @param string $class class name, interface name or alias name
  265. * @return boolean whether the container has the definition of the specified name..
  266. * @see set()
  267. */
  268. public function has($class)
  269. {
  270. return isset($this->_definitions[$class]);
  271. }
  272. /**
  273. * Returns a value indicating whether the given name corresponds to a registered singleton.
  274. * @param string $class class name, interface name or alias name
  275. * @param boolean $checkInstance whether to check if the singleton has been instantiated.
  276. * @return boolean whether the given name corresponds to a registered singleton. If `$checkInstance` is true,
  277. * the method should return a value indicating whether the singleton has been instantiated.
  278. */
  279. public function hasSingleton($class, $checkInstance = false)
  280. {
  281. return $checkInstance ? isset($this->_singletons[$class]) : array_key_exists($class, $this->_singletons);
  282. }
  283. /**
  284. * Removes the definition for the specified name.
  285. * @param string $class class name, interface name or alias name
  286. */
  287. public function clear($class)
  288. {
  289. unset($this->_definitions[$class], $this->_singletons[$class]);
  290. }
  291. /**
  292. * Normalizes the class definition.
  293. * @param string $class class name
  294. * @param string|array|callable $definition the class definition
  295. * @return array the normalized class definition
  296. * @throws InvalidConfigException if the definition is invalid.
  297. */
  298. protected function normalizeDefinition($class, $definition)
  299. {
  300. if (empty($definition)) {
  301. return ['class' => $class];
  302. } elseif (is_string($definition)) {
  303. return ['class' => $definition];
  304. } elseif (is_callable($definition, true) || is_object($definition)) {
  305. return $definition;
  306. } elseif (is_array($definition)) {
  307. if (!isset($definition['class'])) {
  308. if (strpos($class, '\\') !== false) {
  309. $definition['class'] = $class;
  310. } else {
  311. throw new InvalidConfigException("A class definition requires a \"class\" member.");
  312. }
  313. }
  314. return $definition;
  315. } else {
  316. throw new InvalidConfigException("Unsupported definition type for \"$class\": " . gettype($definition));
  317. }
  318. }
  319. /**
  320. * Returns the list of the object definitions or the loaded shared objects.
  321. * @return array the list of the object definitions or the loaded shared objects (type or ID => definition or instance).
  322. */
  323. public function getDefinitions()
  324. {
  325. return $this->_definitions;
  326. }
  327. /**
  328. * Creates an instance of the specified class.
  329. * This method will resolve dependencies of the specified class, instantiate them, and inject
  330. * them into the new instance of the specified class.
  331. * @param string $class the class name
  332. * @param array $params constructor parameters
  333. * @param array $config configurations to be applied to the new instance
  334. * @return object the newly created instance of the specified class
  335. */
  336. protected function build($class, $params, $config)
  337. {
  338. /* @var $reflection ReflectionClass */
  339. list ($reflection, $dependencies) = $this->getDependencies($class);
  340. foreach ($params as $index => $param) {
  341. $dependencies[$index] = $param;
  342. }
  343. $dependencies = $this->resolveDependencies($dependencies, $reflection);
  344. if (empty($config)) {
  345. return $reflection->newInstanceArgs($dependencies);
  346. }
  347. if (!empty($dependencies) && $reflection->implementsInterface('yii\base\Configurable')) {
  348. // set $config as the last parameter (existing one will be overwritten)
  349. $dependencies[count($dependencies) - 1] = $config;
  350. return $reflection->newInstanceArgs($dependencies);
  351. } else {
  352. $object = $reflection->newInstanceArgs($dependencies);
  353. foreach ($config as $name => $value) {
  354. $object->$name = $value;
  355. }
  356. return $object;
  357. }
  358. }
  359. /**
  360. * Merges the user-specified constructor parameters with the ones registered via [[set()]].
  361. * @param string $class class name, interface name or alias name
  362. * @param array $params the constructor parameters
  363. * @return array the merged parameters
  364. */
  365. protected function mergeParams($class, $params)
  366. {
  367. if (empty($this->_params[$class])) {
  368. return $params;
  369. } elseif (empty($params)) {
  370. return $this->_params[$class];
  371. } else {
  372. $ps = $this->_params[$class];
  373. foreach ($params as $index => $value) {
  374. $ps[$index] = $value;
  375. }
  376. return $ps;
  377. }
  378. }
  379. /**
  380. * Returns the dependencies of the specified class.
  381. * @param string $class class name, interface name or alias name
  382. * @return array the dependencies of the specified class.
  383. */
  384. protected function getDependencies($class)
  385. {
  386. if (isset($this->_reflections[$class])) {
  387. return [$this->_reflections[$class], $this->_dependencies[$class]];
  388. }
  389. $dependencies = [];
  390. $reflection = new ReflectionClass($class);
  391. $constructor = $reflection->getConstructor();
  392. if ($constructor !== null) {
  393. foreach ($constructor->getParameters() as $param) {
  394. if ($param->isDefaultValueAvailable()) {
  395. $dependencies[] = $param->getDefaultValue();
  396. } else {
  397. $c = $param->getClass();
  398. $dependencies[] = Instance::of($c === null ? null : $c->getName());
  399. }
  400. }
  401. }
  402. $this->_reflections[$class] = $reflection;
  403. $this->_dependencies[$class] = $dependencies;
  404. return [$reflection, $dependencies];
  405. }
  406. /**
  407. * Resolves dependencies by replacing them with the actual object instances.
  408. * @param array $dependencies the dependencies
  409. * @param ReflectionClass $reflection the class reflection associated with the dependencies
  410. * @return array the resolved dependencies
  411. * @throws InvalidConfigException if a dependency cannot be resolved or if a dependency cannot be fulfilled.
  412. */
  413. protected function resolveDependencies($dependencies, $reflection = null)
  414. {
  415. foreach ($dependencies as $index => $dependency) {
  416. if ($dependency instanceof Instance) {
  417. if ($dependency->id !== null) {
  418. $dependencies[$index] = $this->get($dependency->id);
  419. } elseif ($reflection !== null) {
  420. $name = $reflection->getConstructor()->getParameters()[$index]->getName();
  421. $class = $reflection->getName();
  422. throw new InvalidConfigException("Missing required parameter \"$name\" when instantiating \"$class\".");
  423. }
  424. }
  425. }
  426. return $dependencies;
  427. }
  428. }