ClassRegistry.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (http://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. (http://cakefoundation.org)
  11. * @link http://cakephp.org CakePHP(tm) Project
  12. * @package Cake.Utility
  13. * @since CakePHP(tm) v 0.9.2
  14. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  15. */
  16. /**
  17. * Included libraries.
  18. */
  19. App::uses('Model', 'Model');
  20. App::uses('AppModel', 'Model');
  21. App::uses('ConnectionManager', 'Model');
  22. /**
  23. * Class Collections.
  24. *
  25. * A repository for class objects, each registered with a key.
  26. * If you try to add an object with the same key twice, nothing will come of it.
  27. * If you need a second instance of an object, give it another key.
  28. *
  29. * @package Cake.Utility
  30. */
  31. class ClassRegistry {
  32. /**
  33. * Names of classes with their objects.
  34. *
  35. * @var array
  36. */
  37. protected $_objects = array();
  38. /**
  39. * Names of class names mapped to the object in the registry.
  40. *
  41. * @var array
  42. */
  43. protected $_map = array();
  44. /**
  45. * Default constructor parameter settings, indexed by type
  46. *
  47. * @var array
  48. */
  49. protected $_config = array();
  50. /**
  51. * Return a singleton instance of the ClassRegistry.
  52. *
  53. * @return ClassRegistry instance
  54. */
  55. public static function getInstance() {
  56. static $instance = array();
  57. if (!$instance) {
  58. $instance[0] = new ClassRegistry();
  59. }
  60. return $instance[0];
  61. }
  62. /**
  63. * Loads a class, registers the object in the registry and returns instance of the object. ClassRegistry::init()
  64. * is used as a factory for models, and handle correct injecting of settings, that assist in testing.
  65. *
  66. * Examples
  67. * Simple Use: Get a Post model instance ```ClassRegistry::init('Post');```
  68. *
  69. * Expanded: ```array('class' => 'ClassName', 'alias' => 'AliasNameStoredInTheRegistry');```
  70. *
  71. * Model Classes can accept optional ```array('id' => $id, 'table' => $table, 'ds' => $ds, 'alias' => $alias);```
  72. *
  73. * When $class is a numeric keyed array, multiple class instances will be stored in the registry,
  74. * no instance of the object will be returned
  75. * {{{
  76. * array(
  77. * array('class' => 'ClassName', 'alias' => 'AliasNameStoredInTheRegistry'),
  78. * array('class' => 'ClassName', 'alias' => 'AliasNameStoredInTheRegistry'),
  79. * array('class' => 'ClassName', 'alias' => 'AliasNameStoredInTheRegistry')
  80. * );
  81. * }}}
  82. * @param string|array $class as a string or a single key => value array instance will be created,
  83. * stored in the registry and returned.
  84. * @param boolean $strict if set to true it will return false if the class was not found instead
  85. * of trying to create an AppModel
  86. * @return object instance of ClassName.
  87. * @throws CakeException when you try to construct an interface or abstract class.
  88. */
  89. public static function init($class, $strict = false) {
  90. $_this = ClassRegistry::getInstance();
  91. if (is_array($class)) {
  92. $objects = $class;
  93. if (!isset($class[0])) {
  94. $objects = array($class);
  95. }
  96. } else {
  97. $objects = array(array('class' => $class));
  98. }
  99. $defaults = array();
  100. if (isset($_this->_config['Model'])) {
  101. $defaults = $_this->_config['Model'];
  102. }
  103. $count = count($objects);
  104. $availableDs = null;
  105. foreach ($objects as $settings) {
  106. if (is_numeric($settings)) {
  107. trigger_error(__d('cake_dev', '(ClassRegistry::init() Attempted to create instance of a class with a numeric name'), E_USER_WARNING);
  108. return false;
  109. }
  110. if (is_array($settings)) {
  111. $pluginPath = null;
  112. $settings = array_merge($defaults, $settings);
  113. $class = $settings['class'];
  114. list($plugin, $class) = pluginSplit($class);
  115. if ($plugin) {
  116. $pluginPath = $plugin . '.';
  117. $settings['plugin'] = $plugin;
  118. }
  119. if (empty($settings['alias'])) {
  120. $settings['alias'] = $class;
  121. }
  122. $alias = $settings['alias'];
  123. $model = $_this->_duplicate($alias, $class);
  124. if ($model) {
  125. $_this->map($alias, $class);
  126. return $model;
  127. }
  128. App::uses($plugin . 'AppModel', $pluginPath . 'Model');
  129. App::uses($class, $pluginPath . 'Model');
  130. if (class_exists($class) || interface_exists($class)) {
  131. $reflection = new ReflectionClass($class);
  132. if ($reflection->isAbstract() || $reflection->isInterface()) {
  133. throw new CakeException(__d('cake_dev', 'Cannot create instance of %s, as it is abstract or is an interface', $class));
  134. }
  135. $testing = isset($settings['testing']) ? $settings['testing'] : false;
  136. if ($testing) {
  137. $settings['ds'] = 'test';
  138. $defaultProperties = $reflection->getDefaultProperties();
  139. if (isset($defaultProperties['useDbConfig'])) {
  140. $useDbConfig = $defaultProperties['useDbConfig'];
  141. if ($availableDs === null) {
  142. $availableDs = array_keys(ConnectionManager::enumConnectionObjects());
  143. }
  144. if (in_array('test_' . $useDbConfig, $availableDs)) {
  145. $useDbConfig = 'test_' . $useDbConfig;
  146. }
  147. if (strpos($useDbConfig, 'test') === 0) {
  148. $settings['ds'] = $useDbConfig;
  149. }
  150. }
  151. }
  152. if ($reflection->getConstructor()) {
  153. $instance = $reflection->newInstance($settings);
  154. } else {
  155. $instance = $reflection->newInstance();
  156. }
  157. if ($strict && !$instance instanceof Model) {
  158. $instance = null;
  159. }
  160. }
  161. if (!isset($instance)) {
  162. $appModel = 'AppModel';
  163. if ($strict) {
  164. return false;
  165. } elseif ($plugin && class_exists($plugin . 'AppModel')) {
  166. $appModel = $plugin . 'AppModel';
  167. }
  168. if (!empty($appModel)) {
  169. $settings['name'] = $class;
  170. $instance = new $appModel($settings);
  171. }
  172. if (!isset($instance)) {
  173. trigger_error(__d('cake_dev', '(ClassRegistry::init() could not create instance of %s', $class), E_USER_WARNING);
  174. return false;
  175. }
  176. }
  177. $_this->map($alias, $class);
  178. }
  179. }
  180. if ($count > 1) {
  181. return true;
  182. }
  183. return $instance;
  184. }
  185. /**
  186. * Add $object to the registry, associating it with the name $key.
  187. *
  188. * @param string $key Key for the object in registry
  189. * @param object $object Object to store
  190. * @return boolean True if the object was written, false if $key already exists
  191. */
  192. public static function addObject($key, $object) {
  193. $_this = ClassRegistry::getInstance();
  194. $key = Inflector::underscore($key);
  195. if (!isset($_this->_objects[$key])) {
  196. $_this->_objects[$key] = $object;
  197. return true;
  198. }
  199. return false;
  200. }
  201. /**
  202. * Remove object which corresponds to given key.
  203. *
  204. * @param string $key Key of object to remove from registry
  205. * @return void
  206. */
  207. public static function removeObject($key) {
  208. $_this = ClassRegistry::getInstance();
  209. $key = Inflector::underscore($key);
  210. if (isset($_this->_objects[$key])) {
  211. unset($_this->_objects[$key]);
  212. }
  213. }
  214. /**
  215. * Returns true if given key is present in the ClassRegistry.
  216. *
  217. * @param string $key Key to look for
  218. * @return boolean true if key exists in registry, false otherwise
  219. */
  220. public static function isKeySet($key) {
  221. $_this = ClassRegistry::getInstance();
  222. $key = Inflector::underscore($key);
  223. return isset($_this->_objects[$key]) || isset($_this->_map[$key]);
  224. }
  225. /**
  226. * Get all keys from the registry.
  227. *
  228. * @return array Set of keys stored in registry
  229. */
  230. public static function keys() {
  231. return array_keys(ClassRegistry::getInstance()->_objects);
  232. }
  233. /**
  234. * Return object which corresponds to given key.
  235. *
  236. * @param string $key Key of object to look for
  237. * @return mixed Object stored in registry or boolean false if the object does not exist.
  238. */
  239. public static function getObject($key) {
  240. $_this = ClassRegistry::getInstance();
  241. $key = Inflector::underscore($key);
  242. $return = false;
  243. if (isset($_this->_objects[$key])) {
  244. $return = $_this->_objects[$key];
  245. } else {
  246. $key = $_this->_getMap($key);
  247. if (isset($_this->_objects[$key])) {
  248. $return = $_this->_objects[$key];
  249. }
  250. }
  251. return $return;
  252. }
  253. /**
  254. * Sets the default constructor parameter for an object type
  255. *
  256. * @param string $type Type of object. If this parameter is omitted, defaults to "Model"
  257. * @param array $param The parameter that will be passed to object constructors when objects
  258. * of $type are created
  259. * @return mixed Void if $param is being set. Otherwise, if only $type is passed, returns
  260. * the previously-set value of $param, or null if not set.
  261. */
  262. public static function config($type, $param = array()) {
  263. $_this = ClassRegistry::getInstance();
  264. if (empty($param) && is_array($type)) {
  265. $param = $type;
  266. $type = 'Model';
  267. } elseif ($param === null) {
  268. unset($_this->_config[$type]);
  269. } elseif (empty($param) && is_string($type)) {
  270. return isset($_this->_config[$type]) ? $_this->_config[$type] : null;
  271. }
  272. if (isset($_this->_config[$type]['testing'])) {
  273. $param['testing'] = true;
  274. }
  275. $_this->_config[$type] = $param;
  276. }
  277. /**
  278. * Checks to see if $alias is a duplicate $class Object
  279. *
  280. * @param string $alias
  281. * @param string $class
  282. * @return boolean
  283. */
  284. protected function &_duplicate($alias, $class) {
  285. $duplicate = false;
  286. if ($this->isKeySet($alias)) {
  287. $model = $this->getObject($alias);
  288. if (is_object($model) && ($model instanceof $class || $model->alias === $class)) {
  289. $duplicate = $model;
  290. }
  291. unset($model);
  292. }
  293. return $duplicate;
  294. }
  295. /**
  296. * Add a key name pair to the registry to map name to class in the registry.
  297. *
  298. * @param string $key Key to include in map
  299. * @param string $name Key that is being mapped
  300. * @return void
  301. */
  302. public static function map($key, $name) {
  303. $_this = ClassRegistry::getInstance();
  304. $key = Inflector::underscore($key);
  305. $name = Inflector::underscore($name);
  306. if (!isset($_this->_map[$key])) {
  307. $_this->_map[$key] = $name;
  308. }
  309. }
  310. /**
  311. * Get all keys from the map in the registry.
  312. *
  313. * @return array Keys of registry's map
  314. */
  315. public static function mapKeys() {
  316. return array_keys(ClassRegistry::getInstance()->_map);
  317. }
  318. /**
  319. * Return the name of a class in the registry.
  320. *
  321. * @param string $key Key to find in map
  322. * @return string Mapped value
  323. */
  324. protected function _getMap($key) {
  325. if (isset($this->_map[$key])) {
  326. return $this->_map[$key];
  327. }
  328. }
  329. /**
  330. * Flushes all objects from the ClassRegistry.
  331. *
  332. * @return void
  333. */
  334. public static function flush() {
  335. $_this = ClassRegistry::getInstance();
  336. $_this->_objects = array();
  337. $_this->_map = array();
  338. }
  339. }