ObjectRegistry.php 11 KB

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