ObjectRegistry.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  5. *
  6. * Licensed under The MIT License
  7. * For full copyright and license information, please see the LICENSE.txt
  8. * Redistributions of files must retain the above copyright notice.
  9. *
  10. * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  11. * @link https://cakephp.org CakePHP(tm) Project
  12. * @since 3.0.0
  13. * @license https://opensource.org/licenses/mit-license.php MIT License
  14. */
  15. namespace Cake\Core;
  16. use ArrayIterator;
  17. use Cake\Event\EventDispatcherInterface;
  18. use Cake\Event\EventListenerInterface;
  19. use Countable;
  20. use IteratorAggregate;
  21. use RuntimeException;
  22. /**
  23. * Acts as a registry/factory for objects.
  24. *
  25. * Provides registry & factory functionality for object types. Used
  26. * as a super class for various composition based re-use features in CakePHP.
  27. *
  28. * Each subclass needs to implement the various abstract methods to complete
  29. * the template method load().
  30. *
  31. * The ObjectRegistry is EventManager aware, but each extending class will need to use
  32. * \Cake\Event\EventDispatcherTrait to attach and detach on set and bind
  33. *
  34. * @see \Cake\Controller\ComponentRegistry
  35. * @see \Cake\View\HelperRegistry
  36. * @see \Cake\Console\TaskRegistry
  37. */
  38. abstract class ObjectRegistry implements Countable, IteratorAggregate
  39. {
  40. /**
  41. * Map of loaded objects.
  42. *
  43. * @var object[]
  44. */
  45. protected $_loaded = [];
  46. /**
  47. * Loads/constructs an object instance.
  48. *
  49. * Will return the instance in the registry if it already exists.
  50. * If a subclass provides event support, you can use `$config['enabled'] = false`
  51. * to exclude constructed objects from being registered for events.
  52. *
  53. * Using Cake\Controller\Controller::$components as an example. You can alias
  54. * an object by setting the 'className' key, i.e.,
  55. *
  56. * ```
  57. * public $components = [
  58. * 'Email' => [
  59. * 'className' => '\App\Controller\Component\AliasedEmailComponent'
  60. * ];
  61. * ];
  62. * ```
  63. *
  64. * All calls to the `Email` component would use `AliasedEmail` instead.
  65. *
  66. * @param string $objectName The name/class of the object to load.
  67. * @param array $config Additional settings to use when loading the object.
  68. * @return mixed
  69. */
  70. public function load($objectName, $config = [])
  71. {
  72. if (is_array($config) && isset($config['className'])) {
  73. $name = $objectName;
  74. $objectName = $config['className'];
  75. } else {
  76. list(, $name) = pluginSplit($objectName);
  77. }
  78. $loaded = isset($this->_loaded[$name]);
  79. if ($loaded && !empty($config)) {
  80. $this->_checkDuplicate($name, $config);
  81. }
  82. if ($loaded) {
  83. return $this->_loaded[$name];
  84. }
  85. $className = $this->_resolveClassName($objectName);
  86. if (!$className || (is_string($className) && !class_exists($className))) {
  87. list($plugin, $objectName) = pluginSplit($objectName);
  88. $this->_throwMissingClassError($objectName, $plugin);
  89. }
  90. $instance = $this->_create($className, $name, $config);
  91. $this->_loaded[$name] = $instance;
  92. return $instance;
  93. }
  94. /**
  95. * Check for duplicate object loading.
  96. *
  97. * If a duplicate is being loaded and has different configuration, that is
  98. * bad and an exception will be raised.
  99. *
  100. * An exception is raised, as replacing the object will not update any
  101. * references other objects may have. Additionally, simply updating the runtime
  102. * configuration is not a good option as we may be missing important constructor
  103. * logic dependent on the configuration.
  104. *
  105. * @param string $name The name of the alias in the registry.
  106. * @param array $config The config data for the new instance.
  107. * @return void
  108. * @throws \RuntimeException When a duplicate is found.
  109. */
  110. protected function _checkDuplicate($name, $config)
  111. {
  112. $existing = $this->_loaded[$name];
  113. $msg = sprintf('The "%s" alias has already been loaded', $name);
  114. $hasConfig = method_exists($existing, 'config');
  115. if (!$hasConfig) {
  116. throw new RuntimeException($msg);
  117. }
  118. if (empty($config)) {
  119. return;
  120. }
  121. $existingConfig = $existing->getConfig();
  122. unset($config['enabled'], $existingConfig['enabled']);
  123. $fail = false;
  124. foreach ($config as $key => $value) {
  125. if (!array_key_exists($key, $existingConfig)) {
  126. $fail = true;
  127. break;
  128. }
  129. if (isset($existingConfig[$key]) && $existingConfig[$key] !== $value) {
  130. $fail = true;
  131. break;
  132. }
  133. }
  134. if ($fail) {
  135. $msg .= ' with the following config: ';
  136. $msg .= var_export($existingConfig, true);
  137. $msg .= ' which differs from ' . var_export($config, true);
  138. throw new RuntimeException($msg);
  139. }
  140. }
  141. /**
  142. * Should resolve the classname for a given object type.
  143. *
  144. * @param string $class The class to resolve.
  145. * @return string|bool The resolved name or false for failure.
  146. */
  147. abstract protected function _resolveClassName($class);
  148. /**
  149. * Throw an exception when the requested object name is missing.
  150. *
  151. * @param string $class The class that is missing.
  152. * @param string $plugin The plugin $class is missing from.
  153. * @return void
  154. * @throws \Exception
  155. */
  156. abstract protected function _throwMissingClassError($class, $plugin);
  157. /**
  158. * Create an instance of a given classname.
  159. *
  160. * This method should construct and do any other initialization logic
  161. * required.
  162. *
  163. * @param string $class The class to build.
  164. * @param string $alias The alias of the object.
  165. * @param array $config The Configuration settings for construction
  166. * @return mixed
  167. */
  168. abstract protected function _create($class, $alias, $config);
  169. /**
  170. * Get the list of loaded objects.
  171. *
  172. * @return array List of object names.
  173. */
  174. public function loaded()
  175. {
  176. return array_keys($this->_loaded);
  177. }
  178. /**
  179. * Check whether or not a given object is loaded.
  180. *
  181. * @param string $name The object name to check for.
  182. * @return bool True is object is loaded else false.
  183. */
  184. public function has($name)
  185. {
  186. return isset($this->_loaded[$name]);
  187. }
  188. /**
  189. * Get loaded object instance.
  190. *
  191. * @param string $name Name of object.
  192. * @return object|null Object instance if loaded else null.
  193. */
  194. public function get($name)
  195. {
  196. if (isset($this->_loaded[$name])) {
  197. return $this->_loaded[$name];
  198. }
  199. return null;
  200. }
  201. /**
  202. * Provide public read access to the loaded objects
  203. *
  204. * @param string $name Name of property to read
  205. * @return mixed
  206. */
  207. public function __get($name)
  208. {
  209. return $this->get($name);
  210. }
  211. /**
  212. * Provide isset access to _loaded
  213. *
  214. * @param string $name Name of object being checked.
  215. * @return bool
  216. */
  217. public function __isset($name)
  218. {
  219. return isset($this->_loaded[$name]);
  220. }
  221. /**
  222. * Sets an object.
  223. *
  224. * @param string $name Name of a property to set.
  225. * @param mixed $object Object to set.
  226. * @return void
  227. */
  228. public function __set($name, $object)
  229. {
  230. $this->set($name, $object);
  231. }
  232. /**
  233. * Unsets an object.
  234. *
  235. * @param string $name Name of a property to unset.
  236. * @return void
  237. */
  238. public function __unset($name)
  239. {
  240. $this->unload($name);
  241. }
  242. /**
  243. * Normalizes an object array, creates an array that makes lazy loading
  244. * easier
  245. *
  246. * @param array $objects Array of child objects to normalize.
  247. * @return array Array of normalized objects.
  248. */
  249. public function normalizeArray($objects)
  250. {
  251. $normal = [];
  252. foreach ($objects as $i => $objectName) {
  253. $config = [];
  254. if (!is_int($i)) {
  255. $config = (array)$objectName;
  256. $objectName = $i;
  257. }
  258. list(, $name) = pluginSplit($objectName);
  259. $normal[$name] = ['class' => $objectName, 'config' => $config];
  260. }
  261. return $normal;
  262. }
  263. /**
  264. * Clear loaded instances in the registry.
  265. *
  266. * If the registry subclass has an event manager, the objects will be detached from events as well.
  267. *
  268. * @return $this
  269. */
  270. public function reset()
  271. {
  272. foreach (array_keys($this->_loaded) as $name) {
  273. $this->unload($name);
  274. }
  275. return $this;
  276. }
  277. /**
  278. * Set an object directly into the registry by name.
  279. *
  280. * If this collection implements events, the passed object will
  281. * be attached into the event manager
  282. *
  283. * @param string $objectName The name of the object to set in the registry.
  284. * @param object $object instance to store in the registry
  285. * @return $this
  286. */
  287. public function set($objectName, $object)
  288. {
  289. list(, $name) = pluginSplit($objectName);
  290. // Just call unload if the object was loaded before
  291. if (array_key_exists($objectName, $this->_loaded)) {
  292. $this->unload($objectName);
  293. }
  294. if ($this instanceof EventDispatcherInterface && $object instanceof EventListenerInterface) {
  295. $this->getEventManager()->on($object);
  296. }
  297. $this->_loaded[$name] = $object;
  298. return $this;
  299. }
  300. /**
  301. * Remove an object from the registry.
  302. *
  303. * If this registry has an event manager, the object will be detached from any events as well.
  304. *
  305. * @param string $objectName The name of the object to remove from the registry.
  306. * @return $this
  307. */
  308. public function unload($objectName)
  309. {
  310. if (empty($this->_loaded[$objectName])) {
  311. list($plugin, $objectName) = pluginSplit($objectName);
  312. $this->_throwMissingClassError($objectName, $plugin);
  313. }
  314. $object = $this->_loaded[$objectName];
  315. if ($this instanceof EventDispatcherInterface && $object instanceof EventListenerInterface) {
  316. $this->getEventManager()->off($object);
  317. }
  318. unset($this->_loaded[$objectName]);
  319. return $this;
  320. }
  321. /**
  322. * Returns an array iterator.
  323. *
  324. * @return \ArrayIterator
  325. */
  326. public function getIterator()
  327. {
  328. return new ArrayIterator($this->_loaded);
  329. }
  330. /**
  331. * Returns the number of loaded objects.
  332. *
  333. * @return int
  334. */
  335. public function count()
  336. {
  337. return count($this->_loaded);
  338. }
  339. /**
  340. * Debug friendly object properties.
  341. *
  342. * @return array
  343. */
  344. public function __debugInfo()
  345. {
  346. $properties = get_object_vars($this);
  347. if (isset($properties['_loaded'])) {
  348. $properties['_loaded'] = array_keys($properties['_loaded']);
  349. }
  350. return $properties;
  351. }
  352. }