ServiceLocator.php 9.2 KB

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