ClassRegistry.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  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. *
  83. * @param string|array $class as a string or a single key => value array instance will be created,
  84. * stored in the registry and returned.
  85. * @param bool $strict if set to true it will return false if the class was not found instead
  86. * of trying to create an AppModel
  87. * @return object instance of ClassName.
  88. * @throws CakeException when you try to construct an interface or abstract class.
  89. */
  90. public static function init($class, $strict = false) {
  91. $_this = ClassRegistry::getInstance();
  92. if (is_array($class)) {
  93. $objects = $class;
  94. if (!isset($class[0])) {
  95. $objects = array($class);
  96. }
  97. } else {
  98. $objects = array(array('class' => $class));
  99. }
  100. $defaults = array();
  101. if (isset($_this->_config['Model'])) {
  102. $defaults = $_this->_config['Model'];
  103. }
  104. $count = count($objects);
  105. $availableDs = null;
  106. foreach ($objects as $settings) {
  107. if (is_numeric($settings)) {
  108. trigger_error(__d('cake_dev', '(ClassRegistry::init() Attempted to create instance of a class with a numeric name'), E_USER_WARNING);
  109. return false;
  110. }
  111. if (is_array($settings)) {
  112. $pluginPath = null;
  113. $settings += $defaults;
  114. $class = $settings['class'];
  115. list($plugin, $class) = pluginSplit($class);
  116. if ($plugin) {
  117. $pluginPath = $plugin . '.';
  118. $settings['plugin'] = $plugin;
  119. }
  120. if (empty($settings['alias'])) {
  121. $settings['alias'] = $class;
  122. }
  123. $alias = $settings['alias'];
  124. $model = $_this->_duplicate($alias, $class);
  125. if ($model) {
  126. $_this->map($alias, $class);
  127. return $model;
  128. }
  129. App::uses($plugin . 'AppModel', $pluginPath . 'Model');
  130. App::uses($class, $pluginPath . 'Model');
  131. if (class_exists($class) || interface_exists($class)) {
  132. $reflection = new ReflectionClass($class);
  133. if ($reflection->isAbstract() || $reflection->isInterface()) {
  134. throw new CakeException(__d('cake_dev', 'Cannot create instance of %s, as it is abstract or is an interface', $class));
  135. }
  136. $testing = isset($settings['testing']) ? $settings['testing'] : false;
  137. if ($testing) {
  138. $settings['ds'] = 'test';
  139. $defaultProperties = $reflection->getDefaultProperties();
  140. if (isset($defaultProperties['useDbConfig'])) {
  141. $useDbConfig = $defaultProperties['useDbConfig'];
  142. if ($availableDs === null) {
  143. $availableDs = array_keys(ConnectionManager::enumConnectionObjects());
  144. }
  145. if (in_array('test_' . $useDbConfig, $availableDs)) {
  146. $useDbConfig = 'test_' . $useDbConfig;
  147. }
  148. if (strpos($useDbConfig, 'test') === 0) {
  149. $settings['ds'] = $useDbConfig;
  150. }
  151. }
  152. }
  153. if ($reflection->getConstructor()) {
  154. $instance = $reflection->newInstance($settings);
  155. } else {
  156. $instance = $reflection->newInstance();
  157. }
  158. if ($strict && !$instance instanceof Model) {
  159. $instance = null;
  160. }
  161. }
  162. if (!isset($instance)) {
  163. $appModel = 'AppModel';
  164. if ($strict) {
  165. return false;
  166. } elseif ($plugin && class_exists($plugin . 'AppModel')) {
  167. $appModel = $plugin . 'AppModel';
  168. }
  169. if (!empty($appModel)) {
  170. $settings['name'] = $class;
  171. $instance = new $appModel($settings);
  172. }
  173. if (!isset($instance)) {
  174. trigger_error(__d('cake_dev', '(ClassRegistry::init() could not create instance of %s', $class), E_USER_WARNING);
  175. return false;
  176. }
  177. }
  178. $_this->map($alias, $class);
  179. }
  180. }
  181. if ($count > 1) {
  182. return true;
  183. }
  184. return $instance;
  185. }
  186. /**
  187. * Add $object to the registry, associating it with the name $key.
  188. *
  189. * @param string $key Key for the object in registry
  190. * @param object $object Object to store
  191. * @return bool True if the object was written, false if $key already exists
  192. */
  193. public static function addObject($key, $object) {
  194. $_this = ClassRegistry::getInstance();
  195. $key = Inflector::underscore($key);
  196. if (!isset($_this->_objects[$key])) {
  197. $_this->_objects[$key] = $object;
  198. return true;
  199. }
  200. return false;
  201. }
  202. /**
  203. * Remove object which corresponds to given key.
  204. *
  205. * @param string $key Key of object to remove from registry
  206. * @return void
  207. */
  208. public static function removeObject($key) {
  209. $_this = ClassRegistry::getInstance();
  210. $key = Inflector::underscore($key);
  211. if (isset($_this->_objects[$key])) {
  212. unset($_this->_objects[$key]);
  213. }
  214. }
  215. /**
  216. * Returns true if given key is present in the ClassRegistry.
  217. *
  218. * @param string $key Key to look for
  219. * @return bool true if key exists in registry, false otherwise
  220. */
  221. public static function isKeySet($key) {
  222. $_this = ClassRegistry::getInstance();
  223. $key = Inflector::underscore($key);
  224. return isset($_this->_objects[$key]) || isset($_this->_map[$key]);
  225. }
  226. /**
  227. * Get all keys from the registry.
  228. *
  229. * @return array Set of keys stored in registry
  230. */
  231. public static function keys() {
  232. return array_keys(ClassRegistry::getInstance()->_objects);
  233. }
  234. /**
  235. * Return object which corresponds to given key.
  236. *
  237. * @param string $key Key of object to look for
  238. * @return mixed Object stored in registry or boolean false if the object does not exist.
  239. */
  240. public static function getObject($key) {
  241. $_this = ClassRegistry::getInstance();
  242. $key = Inflector::underscore($key);
  243. $return = false;
  244. if (isset($_this->_objects[$key])) {
  245. $return = $_this->_objects[$key];
  246. } else {
  247. $key = $_this->_getMap($key);
  248. if (isset($_this->_objects[$key])) {
  249. $return = $_this->_objects[$key];
  250. }
  251. }
  252. return $return;
  253. }
  254. /**
  255. * Sets the default constructor parameter for an object type
  256. *
  257. * @param string $type Type of object. If this parameter is omitted, defaults to "Model"
  258. * @param array $param The parameter that will be passed to object constructors when objects
  259. * of $type are created
  260. * @return mixed Void if $param is being set. Otherwise, if only $type is passed, returns
  261. * the previously-set value of $param, or null if not set.
  262. */
  263. public static function config($type, $param = array()) {
  264. $_this = ClassRegistry::getInstance();
  265. if (empty($param) && is_array($type)) {
  266. $param = $type;
  267. $type = 'Model';
  268. } elseif ($param === null) {
  269. unset($_this->_config[$type]);
  270. } elseif (empty($param) && is_string($type)) {
  271. return isset($_this->_config[$type]) ? $_this->_config[$type] : null;
  272. }
  273. if (isset($_this->_config[$type]['testing'])) {
  274. $param['testing'] = true;
  275. }
  276. $_this->_config[$type] = $param;
  277. }
  278. /**
  279. * Checks to see if $alias is a duplicate $class Object
  280. *
  281. * @param string $alias Alias to check.
  282. * @param string $class Class name.
  283. * @return bool
  284. */
  285. protected function &_duplicate($alias, $class) {
  286. $duplicate = false;
  287. if ($this->isKeySet($alias)) {
  288. $model = $this->getObject($alias);
  289. if (is_object($model) && ($model instanceof $class || $model->alias === $class)) {
  290. $duplicate = $model;
  291. }
  292. unset($model);
  293. }
  294. return $duplicate;
  295. }
  296. /**
  297. * Add a key name pair to the registry to map name to class in the registry.
  298. *
  299. * @param string $key Key to include in map
  300. * @param string $name Key that is being mapped
  301. * @return void
  302. */
  303. public static function map($key, $name) {
  304. $_this = ClassRegistry::getInstance();
  305. $key = Inflector::underscore($key);
  306. $name = Inflector::underscore($name);
  307. if (!isset($_this->_map[$key])) {
  308. $_this->_map[$key] = $name;
  309. }
  310. }
  311. /**
  312. * Get all keys from the map in the registry.
  313. *
  314. * @return array Keys of registry's map
  315. */
  316. public static function mapKeys() {
  317. return array_keys(ClassRegistry::getInstance()->_map);
  318. }
  319. /**
  320. * Return the name of a class in the registry.
  321. *
  322. * @param string $key Key to find in map
  323. * @return string Mapped value
  324. */
  325. protected function _getMap($key) {
  326. if (isset($this->_map[$key])) {
  327. return $this->_map[$key];
  328. }
  329. }
  330. /**
  331. * Flushes all objects from the ClassRegistry.
  332. *
  333. * @return void
  334. */
  335. public static function flush() {
  336. $_this = ClassRegistry::getInstance();
  337. $_this->_objects = array();
  338. $_this->_map = array();
  339. }
  340. }