Cache.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  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.Cache
  12. * @since CakePHP(tm) v 1.2.0.4933
  13. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  14. */
  15. App::uses('Inflector', 'Utility');
  16. App::uses('CacheEngine', 'Cache');
  17. /**
  18. * Cache provides a consistent interface to Caching in your application. It allows you
  19. * to use several different Cache engines, without coupling your application to a specific
  20. * implementation. It also allows you to change out cache storage or configuration without effecting
  21. * the rest of your application.
  22. *
  23. * You can configure Cache engines in your application's `bootstrap.php` file. A sample configuration would
  24. * be
  25. *
  26. * {{{
  27. * Cache::config('shared', array(
  28. * 'engine' => 'Apc',
  29. * 'prefix' => 'my_app_'
  30. * ));
  31. * }}}
  32. *
  33. * This would configure an APC cache engine to the 'shared' alias. You could then read and write
  34. * to that cache alias by using it for the `$config` parameter in the various Cache methods. In
  35. * general all Cache operations are supported by all cache engines. However, Cache::increment() and
  36. * Cache::decrement() are not supported by File caching.
  37. *
  38. * @package Cake.Cache
  39. */
  40. class Cache {
  41. /**
  42. * Cache configuration stack
  43. * Keeps the permanent/default settings for each cache engine.
  44. * These settings are used to reset the engines after temporary modification.
  45. *
  46. * @var array
  47. */
  48. protected static $_config = array();
  49. /**
  50. * Whether to reset the settings with the next call to Cache::set();
  51. *
  52. * @var array
  53. */
  54. protected static $_reset = false;
  55. /**
  56. * Engine instances keyed by configuration name.
  57. *
  58. * @var array
  59. */
  60. protected static $_engines = array();
  61. /**
  62. * Set the cache configuration to use. config() can
  63. * both create new configurations, return the settings for already configured
  64. * configurations.
  65. *
  66. * To create a new configuration, or to modify an existing configuration permanently:
  67. *
  68. * `Cache::config('my_config', array('engine' => 'File', 'path' => TMP));`
  69. *
  70. * If you need to modify a configuration temporarily, use Cache::set().
  71. * To get the settings for a configuration:
  72. *
  73. * `Cache::config('default');`
  74. *
  75. * There are 5 built-in caching engines:
  76. *
  77. * - `FileEngine` - Uses simple files to store content. Poor performance, but good for
  78. * storing large objects, or things that are not IO sensitive.
  79. * - `ApcEngine` - Uses the APC object cache, one of the fastest caching engines.
  80. * - `MemcacheEngine` - Uses the PECL::Memcache extension and Memcached for storage.
  81. * Fast reads/writes, and benefits from memcache being distributed.
  82. * - `XcacheEngine` - Uses the Xcache extension, an alternative to APC.
  83. * - `WincacheEngine` - Uses Windows Cache Extension for PHP. Supports wincache 1.1.0 and higher.
  84. *
  85. * The following keys are used in core cache engines:
  86. *
  87. * - `duration` Specify how long items in this cache configuration last.
  88. * - `groups` List of groups or 'tags' associated to every key stored in this config.
  89. * handy for deleting a complete group from cache.
  90. * - `prefix` Prefix appended to all entries. Good for when you need to share a keyspace
  91. * with either another cache config or another application.
  92. * - `probability` Probability of hitting a cache gc cleanup. Setting to 0 will disable
  93. * cache::gc from ever being called automatically.
  94. * - `servers' Used by memcache. Give the address of the memcached servers to use.
  95. * - `compress` Used by memcache. Enables memcache's compressed format.
  96. * - `serialize` Used by FileCache. Should cache objects be serialized first.
  97. * - `path` Used by FileCache. Path to where cachefiles should be saved.
  98. * - `lock` Used by FileCache. Should files be locked before writing to them?
  99. * - `user` Used by Xcache. Username for XCache
  100. * - `password` Used by Xcache/Redis. Password for XCache/Redis
  101. *
  102. * @see app/Config/core.php for configuration settings
  103. * @param string $name Name of the configuration
  104. * @param array $settings Optional associative array of settings passed to the engine
  105. * @return array array(engine, settings) on success, false on failure
  106. * @throws CacheException
  107. */
  108. public static function config($name = null, $settings = array()) {
  109. if (is_array($name)) {
  110. $settings = $name;
  111. }
  112. $current = array();
  113. if (isset(self::$_config[$name])) {
  114. $current = self::$_config[$name];
  115. }
  116. if (!empty($settings)) {
  117. self::$_config[$name] = array_merge($current, $settings);
  118. }
  119. if (empty(self::$_config[$name]['engine'])) {
  120. return false;
  121. }
  122. $engine = self::$_config[$name]['engine'];
  123. if (!isset(self::$_engines[$name])) {
  124. self::_buildEngine($name);
  125. $settings = self::$_config[$name] = self::settings($name);
  126. } elseif ($settings = self::set(self::$_config[$name], null, $name)) {
  127. self::$_config[$name] = $settings;
  128. }
  129. return compact('engine', 'settings');
  130. }
  131. /**
  132. * Finds and builds the instance of the required engine class.
  133. *
  134. * @param string $name Name of the config array that needs an engine instance built
  135. * @return boolean
  136. * @throws CacheException
  137. */
  138. protected static function _buildEngine($name) {
  139. $config = self::$_config[$name];
  140. list($plugin, $class) = pluginSplit($config['engine'], true);
  141. $cacheClass = $class . 'Engine';
  142. App::uses($cacheClass, $plugin . 'Cache/Engine');
  143. if (!class_exists($cacheClass)) {
  144. throw new CacheException(__d('cake_dev', 'Cache engine %s is not available.', $name));
  145. }
  146. $cacheClass = $class . 'Engine';
  147. if (!is_subclass_of($cacheClass, 'CacheEngine')) {
  148. throw new CacheException(__d('cake_dev', 'Cache engines must use CacheEngine as a base class.'));
  149. }
  150. self::$_engines[$name] = new $cacheClass();
  151. if (!self::$_engines[$name]->init($config)) {
  152. throw new CacheException(__d('cake_dev', 'Cache engine %s is not properly configured.', $name));
  153. }
  154. if (self::$_engines[$name]->settings['probability'] && time() % self::$_engines[$name]->settings['probability'] === 0) {
  155. self::$_engines[$name]->gc();
  156. }
  157. return true;
  158. }
  159. /**
  160. * Returns an array containing the currently configured Cache settings.
  161. *
  162. * @return array Array of configured Cache config names.
  163. */
  164. public static function configured() {
  165. return array_keys(self::$_config);
  166. }
  167. /**
  168. * Drops a cache engine. Deletes the cache configuration information
  169. * If the deleted configuration is the last configuration using an certain engine,
  170. * the Engine instance is also unset.
  171. *
  172. * @param string $name A currently configured cache config you wish to remove.
  173. * @return boolean success of the removal, returns false when the config does not exist.
  174. */
  175. public static function drop($name) {
  176. if (!isset(self::$_config[$name])) {
  177. return false;
  178. }
  179. unset(self::$_config[$name], self::$_engines[$name]);
  180. return true;
  181. }
  182. /**
  183. * Temporarily change the settings on a cache config. The settings will persist for the next write
  184. * operation (write, decrement, increment, clear). Any reads that are done before the write, will
  185. * use the modified settings. If `$settings` is empty, the settings will be reset to the
  186. * original configuration.
  187. *
  188. * Can be called with 2 or 3 parameters. To set multiple values at once.
  189. *
  190. * `Cache::set(array('duration' => '+30 minutes'), 'my_config');`
  191. *
  192. * Or to set one value.
  193. *
  194. * `Cache::set('duration', '+30 minutes', 'my_config');`
  195. *
  196. * To reset a config back to the originally configured values.
  197. *
  198. * `Cache::set(null, 'my_config');`
  199. *
  200. * @param string|array $settings Optional string for simple name-value pair or array
  201. * @param string $value Optional for a simple name-value pair
  202. * @param string $config The configuration name you are changing. Defaults to 'default'
  203. * @return array Array of settings.
  204. */
  205. public static function set($settings = array(), $value = null, $config = 'default') {
  206. if (is_array($settings) && $value !== null) {
  207. $config = $value;
  208. }
  209. if (!isset(self::$_config[$config]) || !isset(self::$_engines[$config])) {
  210. return false;
  211. }
  212. if (!empty($settings)) {
  213. self::$_reset = true;
  214. }
  215. if (self::$_reset === true) {
  216. if (empty($settings)) {
  217. self::$_reset = false;
  218. $settings = self::$_config[$config];
  219. } else {
  220. if (is_string($settings) && $value !== null) {
  221. $settings = array($settings => $value);
  222. }
  223. $settings = array_merge(self::$_config[$config], $settings);
  224. if (isset($settings['duration']) && !is_numeric($settings['duration'])) {
  225. $settings['duration'] = strtotime($settings['duration']) - time();
  226. }
  227. }
  228. self::$_engines[$config]->settings = $settings;
  229. }
  230. return self::settings($config);
  231. }
  232. /**
  233. * Garbage collection
  234. *
  235. * Permanently remove all expired and deleted data
  236. *
  237. * @param string $config [optional] The config name you wish to have garbage collected. Defaults to 'default'
  238. * @param integer $expires [optional] An expires timestamp. Defaults to NULL
  239. * @return void
  240. */
  241. public static function gc($config = 'default', $expires = null) {
  242. self::$_engines[$config]->gc($expires);
  243. }
  244. /**
  245. * Write data for key into cache. Will automatically use the currently
  246. * active cache configuration. To set the currently active configuration use
  247. * Cache::config()
  248. *
  249. * ### Usage:
  250. *
  251. * Writing to the active cache config:
  252. *
  253. * `Cache::write('cached_data', $data);`
  254. *
  255. * Writing to a specific cache config:
  256. *
  257. * `Cache::write('cached_data', $data, 'long_term');`
  258. *
  259. * @param string $key Identifier for the data
  260. * @param mixed $value Data to be cached - anything except a resource
  261. * @param string $config Optional string configuration name to write to. Defaults to 'default'
  262. * @return boolean True if the data was successfully cached, false on failure
  263. */
  264. public static function write($key, $value, $config = 'default') {
  265. $settings = self::settings($config);
  266. if (empty($settings)) {
  267. return false;
  268. }
  269. if (!self::isInitialized($config)) {
  270. return false;
  271. }
  272. $key = self::$_engines[$config]->key($key);
  273. if (!$key || is_resource($value)) {
  274. return false;
  275. }
  276. $success = self::$_engines[$config]->write($settings['prefix'] . $key, $value, $settings['duration']);
  277. self::set(null, $config);
  278. if ($success === false && $value !== '') {
  279. trigger_error(
  280. __d('cake_dev',
  281. "%s cache was unable to write '%s' to %s cache",
  282. $config,
  283. $key,
  284. self::$_engines[$config]->settings['engine']
  285. ),
  286. E_USER_WARNING
  287. );
  288. }
  289. return $success;
  290. }
  291. /**
  292. * Read a key from the cache. Will automatically use the currently
  293. * active cache configuration. To set the currently active configuration use
  294. * Cache::config()
  295. *
  296. * ### Usage:
  297. *
  298. * Reading from the active cache configuration.
  299. *
  300. * `Cache::read('my_data');`
  301. *
  302. * Reading from a specific cache configuration.
  303. *
  304. * `Cache::read('my_data', 'long_term');`
  305. *
  306. * @param string $key Identifier for the data
  307. * @param string $config optional name of the configuration to use. Defaults to 'default'
  308. * @return mixed The cached data, or false if the data doesn't exist, has expired, or if there was an error fetching it
  309. */
  310. public static function read($key, $config = 'default') {
  311. $settings = self::settings($config);
  312. if (empty($settings)) {
  313. return false;
  314. }
  315. if (!self::isInitialized($config)) {
  316. return false;
  317. }
  318. $key = self::$_engines[$config]->key($key);
  319. if (!$key) {
  320. return false;
  321. }
  322. return self::$_engines[$config]->read($settings['prefix'] . $key);
  323. }
  324. /**
  325. * Increment a number under the key and return incremented value.
  326. *
  327. * @param string $key Identifier for the data
  328. * @param integer $offset How much to add
  329. * @param string $config Optional string configuration name. Defaults to 'default'
  330. * @return mixed new value, or false if the data doesn't exist, is not integer,
  331. * or if there was an error fetching it.
  332. */
  333. public static function increment($key, $offset = 1, $config = 'default') {
  334. $settings = self::settings($config);
  335. if (empty($settings)) {
  336. return false;
  337. }
  338. if (!self::isInitialized($config)) {
  339. return false;
  340. }
  341. $key = self::$_engines[$config]->key($key);
  342. if (!$key || !is_int($offset) || $offset < 0) {
  343. return false;
  344. }
  345. $success = self::$_engines[$config]->increment($settings['prefix'] . $key, $offset);
  346. self::set(null, $config);
  347. return $success;
  348. }
  349. /**
  350. * Decrement a number under the key and return decremented value.
  351. *
  352. * @param string $key Identifier for the data
  353. * @param integer $offset How much to subtract
  354. * @param string $config Optional string configuration name. Defaults to 'default'
  355. * @return mixed new value, or false if the data doesn't exist, is not integer,
  356. * or if there was an error fetching it
  357. */
  358. public static function decrement($key, $offset = 1, $config = 'default') {
  359. $settings = self::settings($config);
  360. if (empty($settings)) {
  361. return false;
  362. }
  363. if (!self::isInitialized($config)) {
  364. return false;
  365. }
  366. $key = self::$_engines[$config]->key($key);
  367. if (!$key || !is_int($offset) || $offset < 0) {
  368. return false;
  369. }
  370. $success = self::$_engines[$config]->decrement($settings['prefix'] . $key, $offset);
  371. self::set(null, $config);
  372. return $success;
  373. }
  374. /**
  375. * Delete a key from the cache.
  376. *
  377. * ### Usage:
  378. *
  379. * Deleting from the active cache configuration.
  380. *
  381. * `Cache::delete('my_data');`
  382. *
  383. * Deleting from a specific cache configuration.
  384. *
  385. * `Cache::delete('my_data', 'long_term');`
  386. *
  387. * @param string $key Identifier for the data
  388. * @param string $config name of the configuration to use. Defaults to 'default'
  389. * @return boolean True if the value was successfully deleted, false if it didn't exist or couldn't be removed
  390. */
  391. public static function delete($key, $config = 'default') {
  392. $settings = self::settings($config);
  393. if (empty($settings)) {
  394. return false;
  395. }
  396. if (!self::isInitialized($config)) {
  397. return false;
  398. }
  399. $key = self::$_engines[$config]->key($key);
  400. if (!$key) {
  401. return false;
  402. }
  403. $success = self::$_engines[$config]->delete($settings['prefix'] . $key);
  404. self::set(null, $config);
  405. return $success;
  406. }
  407. /**
  408. * Delete all keys from the cache.
  409. *
  410. * @param boolean $check if true will check expiration, otherwise delete all
  411. * @param string $config name of the configuration to use. Defaults to 'default'
  412. * @return boolean True if the cache was successfully cleared, false otherwise
  413. */
  414. public static function clear($check = false, $config = 'default') {
  415. if (!self::isInitialized($config)) {
  416. return false;
  417. }
  418. $success = self::$_engines[$config]->clear($check);
  419. self::set(null, $config);
  420. return $success;
  421. }
  422. /**
  423. * Delete all keys from the cache belonging to the same group.
  424. *
  425. * @param string $group name of the group to be cleared
  426. * @param string $config name of the configuration to use. Defaults to 'default'
  427. * @return boolean True if the cache group was successfully cleared, false otherwise
  428. */
  429. public static function clearGroup($group, $config = 'default') {
  430. if (!self::isInitialized($config)) {
  431. return false;
  432. }
  433. $success = self::$_engines[$config]->clearGroup($group);
  434. self::set(null, $config);
  435. return $success;
  436. }
  437. /**
  438. * Check if Cache has initialized a working config for the given name.
  439. *
  440. * @param string $config name of the configuration to use. Defaults to 'default'
  441. * @return boolean Whether or not the config name has been initialized.
  442. */
  443. public static function isInitialized($config = 'default') {
  444. if (Configure::read('Cache.disable')) {
  445. return false;
  446. }
  447. return isset(self::$_engines[$config]);
  448. }
  449. /**
  450. * Return the settings for the named cache engine.
  451. *
  452. * @param string $name Name of the configuration to get settings for. Defaults to 'default'
  453. * @return array list of settings for this engine
  454. * @see Cache::config()
  455. */
  456. public static function settings($name = 'default') {
  457. if (!empty(self::$_engines[$name])) {
  458. return self::$_engines[$name]->settings();
  459. }
  460. return array();
  461. }
  462. }