ClassRegistry.php 10 KB

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