ServiceLocator.php 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  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 Closure;
  9. use Yii;
  10. use yii\base\Component;
  11. use yii\base\InvalidConfigException;
  12. /**
  13. * ServiceLocator implements a [service locator](http://en.wikipedia.org/wiki/Service_locator_pattern).
  14. *
  15. * To use ServiceLocator, you first need to register component IDs with the corresponding component
  16. * definitions with the locator by calling [[set()]] or [[setComponents()]].
  17. * You can then call [[get()]] to retrieve a component with the specified ID. The locator will automatically
  18. * instantiate and configure the component according to the definition.
  19. *
  20. * For example,
  21. *
  22. * ```php
  23. * $locator = new \yii\di\ServiceLocator;
  24. * $locator->setComponents([
  25. * 'db' => [
  26. * 'class' => 'yii\db\Connection',
  27. * 'dsn' => 'sqlite:path/to/file.db',
  28. * ],
  29. * 'cache' => [
  30. * 'class' => 'yii\caching\DbCache',
  31. * 'db' => 'db',
  32. * ],
  33. * ]);
  34. *
  35. * $db = $locator->get('db'); // or $locator->db
  36. * $cache = $locator->get('cache'); // or $locator->cache
  37. * ```
  38. *
  39. * Because [[\yii\base\Module]] extends from ServiceLocator, modules and the application are all service locators.
  40. * Modules add [tree traversal](guide:concept-service-locator#tree-traversal) for service resolution.
  41. *
  42. * For more details and usage information on ServiceLocator, see the [guide article on service locators](guide:concept-service-locator).
  43. *
  44. * @property array $components The list of the component definitions or the loaded component instances (ID =>
  45. * definition or instance).
  46. *
  47. * @author Qiang Xue <qiang.xue@gmail.com>
  48. * @since 2.0
  49. */
  50. class ServiceLocator extends Component
  51. {
  52. /**
  53. * @var array shared component instances indexed by their IDs
  54. */
  55. private $_components = [];
  56. /**
  57. * @var array component definitions indexed by their IDs
  58. */
  59. private $_definitions = [];
  60. /**
  61. * Getter magic method.
  62. * This method is overridden to support accessing components like reading properties.
  63. * @param string $name component or property name
  64. * @return mixed the named property value
  65. */
  66. public function __get($name)
  67. {
  68. if ($this->has($name)) {
  69. return $this->get($name);
  70. }
  71. return parent::__get($name);
  72. }
  73. /**
  74. * Checks if a property value is null.
  75. * This method overrides the parent implementation by checking if the named component is loaded.
  76. * @param string $name the property name or the event name
  77. * @return bool whether the property value is null
  78. */
  79. public function __isset($name)
  80. {
  81. if ($this->has($name)) {
  82. return true;
  83. }
  84. return parent::__isset($name);
  85. }
  86. /**
  87. * Returns a value indicating whether the locator has the specified component definition or has instantiated the component.
  88. * This method may return different results depending on the value of `$checkInstance`.
  89. *
  90. * - If `$checkInstance` is false (default), the method will return a value indicating whether the locator has the specified
  91. * component definition.
  92. * - If `$checkInstance` is true, the method will return a value indicating whether the locator has
  93. * instantiated the specified component.
  94. *
  95. * @param string $id component ID (e.g. `db`).
  96. * @param bool $checkInstance whether the method should check if the component is shared and instantiated.
  97. * @return bool whether the locator has the specified component definition or has instantiated the component.
  98. * @see set()
  99. */
  100. public function has($id, $checkInstance = false)
  101. {
  102. return $checkInstance ? isset($this->_components[$id]) : isset($this->_definitions[$id]);
  103. }
  104. /**
  105. * Returns the component instance with the specified ID.
  106. *
  107. * @param string $id component ID (e.g. `db`).
  108. * @param bool $throwException whether to throw an exception if `$id` is not registered with the locator before.
  109. * @return object|null the component of the specified ID. If `$throwException` is false and `$id`
  110. * is not registered before, null will be returned.
  111. * @throws InvalidConfigException if `$id` refers to a nonexistent component ID
  112. * @see has()
  113. * @see set()
  114. */
  115. public function get($id, $throwException = true)
  116. {
  117. if (isset($this->_components[$id])) {
  118. return $this->_components[$id];
  119. }
  120. if (isset($this->_definitions[$id])) {
  121. $definition = $this->_definitions[$id];
  122. if (is_object($definition) && !$definition instanceof Closure) {
  123. return $this->_components[$id] = $definition;
  124. }
  125. return $this->_components[$id] = Yii::createObject($definition);
  126. } elseif ($throwException) {
  127. throw new InvalidConfigException("Unknown component ID: $id");
  128. }
  129. return null;
  130. }
  131. /**
  132. * Registers a component definition with this locator.
  133. *
  134. * For example,
  135. *
  136. * ```php
  137. * // a class name
  138. * $locator->set('cache', 'yii\caching\FileCache');
  139. *
  140. * // a configuration array
  141. * $locator->set('db', [
  142. * 'class' => 'yii\db\Connection',
  143. * 'dsn' => 'mysql:host=127.0.0.1;dbname=demo',
  144. * 'username' => 'root',
  145. * 'password' => '',
  146. * 'charset' => 'utf8',
  147. * ]);
  148. *
  149. * // an anonymous function
  150. * $locator->set('cache', function ($params) {
  151. * return new \yii\caching\FileCache;
  152. * });
  153. *
  154. * // an instance
  155. * $locator->set('cache', new \yii\caching\FileCache);
  156. * ```
  157. *
  158. * If a component definition with the same ID already exists, it will be overwritten.
  159. *
  160. * @param string $id component ID (e.g. `db`).
  161. * @param mixed $definition the component definition to be registered with this locator.
  162. * It can be one of the following:
  163. *
  164. * - a class name
  165. * - a configuration array: the array contains name-value pairs that will be used to
  166. * initialize the property values of the newly created object when [[get()]] is called.
  167. * The `class` element is required and stands for the the class of the object to be created.
  168. * - a PHP callable: either an anonymous function or an array representing a class method (e.g. `['Foo', 'bar']`).
  169. * The callable will be called by [[get()]] to return an object associated with the specified component ID.
  170. * - an object: When [[get()]] is called, this object will be returned.
  171. *
  172. * @throws InvalidConfigException if the definition is an invalid configuration array
  173. */
  174. public function set($id, $definition)
  175. {
  176. unset($this->_components[$id]);
  177. if ($definition === null) {
  178. unset($this->_definitions[$id]);
  179. return;
  180. }
  181. if (is_object($definition) || is_callable($definition, true)) {
  182. // an object, a class name, or a PHP callable
  183. $this->_definitions[$id] = $definition;
  184. } elseif (is_array($definition)) {
  185. // a configuration array
  186. if (isset($definition['class'])) {
  187. $this->_definitions[$id] = $definition;
  188. } else {
  189. throw new InvalidConfigException("The configuration for the \"$id\" component must contain a \"class\" element.");
  190. }
  191. } else {
  192. throw new InvalidConfigException("Unexpected configuration type for the \"$id\" component: " . gettype($definition));
  193. }
  194. }
  195. /**
  196. * Removes the component from the locator.
  197. * @param string $id the component ID
  198. */
  199. public function clear($id)
  200. {
  201. unset($this->_definitions[$id], $this->_components[$id]);
  202. }
  203. /**
  204. * Returns the list of the component definitions or the loaded component instances.
  205. * @param bool $returnDefinitions whether to return component definitions instead of the loaded component instances.
  206. * @return array the list of the component definitions or the loaded component instances (ID => definition or instance).
  207. */
  208. public function getComponents($returnDefinitions = true)
  209. {
  210. return $returnDefinitions ? $this->_definitions : $this->_components;
  211. }
  212. /**
  213. * Registers a set of component definitions in this locator.
  214. *
  215. * This is the bulk version of [[set()]]. The parameter should be an array
  216. * whose keys are component IDs and values the corresponding component definitions.
  217. *
  218. * For more details on how to specify component IDs and definitions, please refer to [[set()]].
  219. *
  220. * If a component definition with the same ID already exists, it will be overwritten.
  221. *
  222. * The following is an example for registering two component definitions:
  223. *
  224. * ```php
  225. * [
  226. * 'db' => [
  227. * 'class' => 'yii\db\Connection',
  228. * 'dsn' => 'sqlite:path/to/file.db',
  229. * ],
  230. * 'cache' => [
  231. * 'class' => 'yii\caching\DbCache',
  232. * 'db' => 'db',
  233. * ],
  234. * ]
  235. * ```
  236. *
  237. * @param array $components component definitions or instances
  238. */
  239. public function setComponents($components)
  240. {
  241. foreach ($components as $id => $component) {
  242. $this->set($id, $component);
  243. }
  244. }
  245. }