Cache.php 16 KB

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