ClassRegistry.php 10 KB

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