ObjectRegistry.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  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. * @throws \Exception If the class cannot be found.
  70. */
  71. public function load($objectName, $config = [])
  72. {
  73. if (is_array($config) && isset($config['className'])) {
  74. $name = $objectName;
  75. $objectName = $config['className'];
  76. } else {
  77. list(, $name) = pluginSplit($objectName);
  78. }
  79. $loaded = isset($this->_loaded[$name]);
  80. if ($loaded && !empty($config)) {
  81. $this->_checkDuplicate($name, $config);
  82. }
  83. if ($loaded) {
  84. return $this->_loaded[$name];
  85. }
  86. $className = $this->_resolveClassName($objectName);
  87. if (!$className || (is_string($className) && !class_exists($className))) {
  88. list($plugin, $objectName) = pluginSplit($objectName);
  89. $this->_throwMissingClassError($objectName, $plugin);
  90. }
  91. $instance = $this->_create($className, $name, $config);
  92. $this->_loaded[$name] = $instance;
  93. return $instance;
  94. }
  95. /**
  96. * Check for duplicate object loading.
  97. *
  98. * If a duplicate is being loaded and has different configuration, that is
  99. * bad and an exception will be raised.
  100. *
  101. * An exception is raised, as replacing the object will not update any
  102. * references other objects may have. Additionally, simply updating the runtime
  103. * configuration is not a good option as we may be missing important constructor
  104. * logic dependent on the configuration.
  105. *
  106. * @param string $name The name of the alias in the registry.
  107. * @param array $config The config data for the new instance.
  108. * @return void
  109. * @throws \RuntimeException When a duplicate is found.
  110. */
  111. protected function _checkDuplicate($name, $config)
  112. {
  113. /** @var \Cake\Core\InstanceConfigTrait $existing */
  114. $existing = $this->_loaded[$name];
  115. $msg = sprintf('The "%s" alias has already been loaded.', $name);
  116. $hasConfig = method_exists($existing, 'config');
  117. if (!$hasConfig) {
  118. throw new RuntimeException($msg);
  119. }
  120. if (empty($config)) {
  121. return;
  122. }
  123. $existingConfig = $existing->getConfig();
  124. unset($config['enabled'], $existingConfig['enabled']);
  125. $failure = null;
  126. foreach ($config as $key => $value) {
  127. if (!array_key_exists($key, $existingConfig)) {
  128. $failure = " The `{$key}` was not defined in the previous configuration data.";
  129. break;
  130. }
  131. if (isset($existingConfig[$key]) && $existingConfig[$key] !== $value) {
  132. $failure = sprintf(
  133. ' The `%s` key has a value of `%s` but previously had a value of `%s`',
  134. $key,
  135. json_encode($value),
  136. json_encode($existingConfig[$key])
  137. );
  138. break;
  139. }
  140. }
  141. if ($failure) {
  142. throw new RuntimeException($msg . $failure);
  143. }
  144. }
  145. /**
  146. * Should resolve the classname for a given object type.
  147. *
  148. * @param string $class The class to resolve.
  149. * @return string|false The resolved name or false for failure.
  150. */
  151. abstract protected function _resolveClassName($class);
  152. /**
  153. * Throw an exception when the requested object name is missing.
  154. *
  155. * @param string $class The class that is missing.
  156. * @param string|null $plugin The plugin $class is missing from.
  157. * @return void
  158. * @throws \Exception
  159. */
  160. abstract protected function _throwMissingClassError($class, $plugin);
  161. /**
  162. * Create an instance of a given classname.
  163. *
  164. * This method should construct and do any other initialization logic
  165. * required.
  166. *
  167. * @param string $class The class to build.
  168. * @param string $alias The alias of the object.
  169. * @param array $config The Configuration settings for construction
  170. * @return mixed
  171. */
  172. abstract protected function _create($class, $alias, $config);
  173. /**
  174. * Get the list of loaded objects.
  175. *
  176. * @return string[] List of object names.
  177. */
  178. public function loaded()
  179. {
  180. return array_keys($this->_loaded);
  181. }
  182. /**
  183. * Check whether or not a given object is loaded.
  184. *
  185. * @param string $name The object name to check for.
  186. * @return bool True is object is loaded else false.
  187. */
  188. public function has($name)
  189. {
  190. return isset($this->_loaded[$name]);
  191. }
  192. /**
  193. * Get loaded object instance.
  194. *
  195. * @param string $name Name of object.
  196. * @return object|null Object instance if loaded else null.
  197. */
  198. public function get($name)
  199. {
  200. if (isset($this->_loaded[$name])) {
  201. return $this->_loaded[$name];
  202. }
  203. return null;
  204. }
  205. /**
  206. * Provide public read access to the loaded objects
  207. *
  208. * @param string $name Name of property to read
  209. * @return mixed
  210. */
  211. public function __get($name)
  212. {
  213. return $this->get($name);
  214. }
  215. /**
  216. * Provide isset access to _loaded
  217. *
  218. * @param string $name Name of object being checked.
  219. * @return bool
  220. */
  221. public function __isset($name)
  222. {
  223. return isset($this->_loaded[$name]);
  224. }
  225. /**
  226. * Sets an object.
  227. *
  228. * @param string $name Name of a property to set.
  229. * @param mixed $object Object to set.
  230. * @return void
  231. */
  232. public function __set($name, $object)
  233. {
  234. $this->set($name, $object);
  235. }
  236. /**
  237. * Unsets an object.
  238. *
  239. * @param string $name Name of a property to unset.
  240. * @return void
  241. */
  242. public function __unset($name)
  243. {
  244. $this->unload($name);
  245. }
  246. /**
  247. * Normalizes an object array, creates an array that makes lazy loading
  248. * easier
  249. *
  250. * @param array $objects Array of child objects to normalize.
  251. * @return array Array of normalized objects.
  252. */
  253. public function normalizeArray($objects)
  254. {
  255. $normal = [];
  256. foreach ($objects as $i => $objectName) {
  257. $config = [];
  258. if (!is_int($i)) {
  259. $config = (array)$objectName;
  260. $objectName = $i;
  261. }
  262. list(, $name) = pluginSplit($objectName);
  263. if (isset($config['class'])) {
  264. $normal[$name] = $config;
  265. } else {
  266. $normal[$name] = ['class' => $objectName, 'config' => $config];
  267. }
  268. }
  269. return $normal;
  270. }
  271. /**
  272. * Clear loaded instances in the registry.
  273. *
  274. * If the registry subclass has an event manager, the objects will be detached from events as well.
  275. *
  276. * @return $this
  277. */
  278. public function reset()
  279. {
  280. foreach (array_keys($this->_loaded) as $name) {
  281. $this->unload($name);
  282. }
  283. return $this;
  284. }
  285. /**
  286. * Set an object directly into the registry by name.
  287. *
  288. * If this collection implements events, the passed object will
  289. * be attached into the event manager
  290. *
  291. * @param string $objectName The name of the object to set in the registry.
  292. * @param object $object instance to store in the registry
  293. * @return $this
  294. */
  295. public function set($objectName, $object)
  296. {
  297. list(, $name) = pluginSplit($objectName);
  298. // Just call unload if the object was loaded before
  299. if (array_key_exists($objectName, $this->_loaded)) {
  300. $this->unload($objectName);
  301. }
  302. if ($this instanceof EventDispatcherInterface && $object instanceof EventListenerInterface) {
  303. $this->getEventManager()->on($object);
  304. }
  305. $this->_loaded[$name] = $object;
  306. return $this;
  307. }
  308. /**
  309. * Remove an object from the registry.
  310. *
  311. * If this registry has an event manager, the object will be detached from any events as well.
  312. *
  313. * @param string $objectName The name of the object to remove from the registry.
  314. * @return $this
  315. */
  316. public function unload($objectName)
  317. {
  318. if (empty($this->_loaded[$objectName])) {
  319. list($plugin, $objectName) = pluginSplit($objectName);
  320. $this->_throwMissingClassError($objectName, $plugin);
  321. }
  322. $object = $this->_loaded[$objectName];
  323. if ($this instanceof EventDispatcherInterface && $object instanceof EventListenerInterface) {
  324. $this->getEventManager()->off($object);
  325. }
  326. unset($this->_loaded[$objectName]);
  327. return $this;
  328. }
  329. /**
  330. * Returns an array iterator.
  331. *
  332. * @return \ArrayIterator
  333. */
  334. public function getIterator()
  335. {
  336. return new ArrayIterator($this->_loaded);
  337. }
  338. /**
  339. * Returns the number of loaded objects.
  340. *
  341. * @return int
  342. */
  343. public function count()
  344. {
  345. return count($this->_loaded);
  346. }
  347. /**
  348. * Debug friendly object properties.
  349. *
  350. * @return array
  351. */
  352. public function __debugInfo()
  353. {
  354. $properties = get_object_vars($this);
  355. if (isset($properties['_loaded'])) {
  356. $properties['_loaded'] = array_keys($properties['_loaded']);
  357. }
  358. return $properties;
  359. }
  360. }