Cache.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576
  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. * Group to Config mapping
  52. *
  53. * @var array
  54. */
  55. protected static $_groups = array();
  56. /**
  57. * Whether to reset the settings with the next call to Cache::set();
  58. *
  59. * @var array
  60. */
  61. protected static $_reset = false;
  62. /**
  63. * Engine instances keyed by configuration name.
  64. *
  65. * @var array
  66. */
  67. protected static $_engines = array();
  68. /**
  69. * Set the cache configuration to use. config() can
  70. * both create new configurations, return the settings for already configured
  71. * configurations.
  72. *
  73. * To create a new configuration, or to modify an existing configuration permanently:
  74. *
  75. * `Cache::config('my_config', array('engine' => 'File', 'path' => TMP));`
  76. *
  77. * If you need to modify a configuration temporarily, use Cache::set().
  78. * To get the settings for a configuration:
  79. *
  80. * `Cache::config('default');`
  81. *
  82. * There are 5 built-in caching engines:
  83. *
  84. * - `FileEngine` - Uses simple files to store content. Poor performance, but good for
  85. * storing large objects, or things that are not IO sensitive.
  86. * - `ApcEngine` - Uses the APC object cache, one of the fastest caching engines.
  87. * - `MemcacheEngine` - Uses the PECL::Memcache extension and Memcached for storage.
  88. * Fast reads/writes, and benefits from memcache being distributed.
  89. * - `XcacheEngine` - Uses the Xcache extension, an alternative to APC.
  90. * - `WincacheEngine` - Uses Windows Cache Extension for PHP. Supports wincache 1.1.0 and higher.
  91. *
  92. * The following keys are used in core cache engines:
  93. *
  94. * - `duration` Specify how long items in this cache configuration last.
  95. * - `groups` List of groups or 'tags' associated to every key stored in this config.
  96. * handy for deleting a complete group from cache.
  97. * - `prefix` Prefix appended to all entries. Good for when you need to share a keyspace
  98. * with either another cache config or another application.
  99. * - `probability` Probability of hitting a cache gc cleanup. Setting to 0 will disable
  100. * cache::gc from ever being called automatically.
  101. * - `servers' Used by memcache. Give the address of the memcached servers to use.
  102. * - `compress` Used by memcache. Enables memcache's compressed format.
  103. * - `serialize` Used by FileCache. Should cache objects be serialized first.
  104. * - `path` Used by FileCache. Path to where cachefiles should be saved.
  105. * - `lock` Used by FileCache. Should files be locked before writing to them?
  106. * - `user` Used by Xcache. Username for XCache
  107. * - `password` Used by Xcache/Redis. Password for XCache/Redis
  108. *
  109. * @param string $name Name of the configuration
  110. * @param array $settings Optional associative array of settings passed to the engine
  111. * @return array array(engine, settings) on success, false on failure
  112. * @throws CacheException
  113. * @see app/Config/core.php for configuration settings
  114. */
  115. public static function config($name = null, $settings = array()) {
  116. if (is_array($name)) {
  117. $settings = $name;
  118. }
  119. $current = array();
  120. if (isset(self::$_config[$name])) {
  121. $current = self::$_config[$name];
  122. }
  123. if (!empty($settings)) {
  124. self::$_config[$name] = $settings + $current;
  125. }
  126. if (empty(self::$_config[$name]['engine'])) {
  127. return false;
  128. }
  129. if (!empty(self::$_config[$name]['groups'])) {
  130. foreach (self::$_config[$name]['groups'] as $group) {
  131. self::$_groups[$group][] = $name;
  132. sort(self::$_groups[$group]);
  133. self::$_groups[$group] = array_unique(self::$_groups[$group]);
  134. }
  135. }
  136. $engine = self::$_config[$name]['engine'];
  137. if (!isset(self::$_engines[$name])) {
  138. self::_buildEngine($name);
  139. $settings = self::$_config[$name] = self::settings($name);
  140. } elseif ($settings = self::set(self::$_config[$name], null, $name)) {
  141. self::$_config[$name] = $settings;
  142. }
  143. return compact('engine', 'settings');
  144. }
  145. /**
  146. * Finds and builds the instance of the required engine class.
  147. *
  148. * @param string $name Name of the config array that needs an engine instance built
  149. * @return bool
  150. * @throws CacheException
  151. */
  152. protected static function _buildEngine($name) {
  153. $config = self::$_config[$name];
  154. list($plugin, $class) = pluginSplit($config['engine'], true);
  155. $cacheClass = $class . 'Engine';
  156. App::uses($cacheClass, $plugin . 'Cache/Engine');
  157. if (!class_exists($cacheClass)) {
  158. throw new CacheException(__d('cake_dev', 'Cache engine %s is not available.', $name));
  159. }
  160. $cacheClass = $class . 'Engine';
  161. if (!is_subclass_of($cacheClass, 'CacheEngine')) {
  162. throw new CacheException(__d('cake_dev', 'Cache engines must use %s as a base class.', 'CacheEngine'));
  163. }
  164. self::$_engines[$name] = new $cacheClass();
  165. if (!self::$_engines[$name]->init($config)) {
  166. throw new CacheException(__d('cake_dev', 'Cache engine %s is not properly configured.', $name));
  167. }
  168. if (self::$_engines[$name]->settings['probability'] && time() % self::$_engines[$name]->settings['probability'] === 0) {
  169. self::$_engines[$name]->gc();
  170. }
  171. return true;
  172. }
  173. /**
  174. * Returns an array containing the currently configured Cache settings.
  175. *
  176. * @return array Array of configured Cache config names.
  177. */
  178. public static function configured() {
  179. return array_keys(self::$_config);
  180. }
  181. /**
  182. * Drops a cache engine. Deletes the cache configuration information
  183. * If the deleted configuration is the last configuration using an certain engine,
  184. * the Engine instance is also unset.
  185. *
  186. * @param string $name A currently configured cache config you wish to remove.
  187. * @return bool success of the removal, returns false when the config does not exist.
  188. */
  189. public static function drop($name) {
  190. if (!isset(self::$_config[$name])) {
  191. return false;
  192. }
  193. unset(self::$_config[$name], self::$_engines[$name]);
  194. return true;
  195. }
  196. /**
  197. * Temporarily change the settings on a cache config. The settings will persist for the next write
  198. * operation (write, decrement, increment, clear). Any reads that are done before the write, will
  199. * use the modified settings. If `$settings` is empty, the settings will be reset to the
  200. * original configuration.
  201. *
  202. * Can be called with 2 or 3 parameters. To set multiple values at once.
  203. *
  204. * `Cache::set(array('duration' => '+30 minutes'), 'my_config');`
  205. *
  206. * Or to set one value.
  207. *
  208. * `Cache::set('duration', '+30 minutes', 'my_config');`
  209. *
  210. * To reset a config back to the originally configured values.
  211. *
  212. * `Cache::set(null, 'my_config');`
  213. *
  214. * @param string|array $settings Optional string for simple name-value pair or array
  215. * @param string $value Optional for a simple name-value pair
  216. * @param string $config The configuration name you are changing. Defaults to 'default'
  217. * @return array Array of settings.
  218. */
  219. public static function set($settings = array(), $value = null, $config = 'default') {
  220. if (is_array($settings) && $value !== null) {
  221. $config = $value;
  222. }
  223. if (!isset(self::$_config[$config]) || !isset(self::$_engines[$config])) {
  224. return false;
  225. }
  226. if (!empty($settings)) {
  227. self::$_reset = true;
  228. }
  229. if (self::$_reset === true) {
  230. if (empty($settings)) {
  231. self::$_reset = false;
  232. $settings = self::$_config[$config];
  233. } else {
  234. if (is_string($settings) && $value !== null) {
  235. $settings = array($settings => $value);
  236. }
  237. $settings += self::$_config[$config];
  238. if (isset($settings['duration']) && !is_numeric($settings['duration'])) {
  239. $settings['duration'] = strtotime($settings['duration']) - time();
  240. }
  241. }
  242. self::$_engines[$config]->settings = $settings;
  243. }
  244. return self::settings($config);
  245. }
  246. /**
  247. * Garbage collection
  248. *
  249. * Permanently remove all expired and deleted data
  250. *
  251. * @param string $config [optional] The config name you wish to have garbage collected. Defaults to 'default'
  252. * @param int $expires [optional] An expires timestamp. Defaults to NULL
  253. * @return void
  254. */
  255. public static function gc($config = 'default', $expires = null) {
  256. self::$_engines[$config]->gc($expires);
  257. }
  258. /**
  259. * Write data for key into a cache engine.
  260. *
  261. * ### Usage:
  262. *
  263. * Writing to the active cache config:
  264. *
  265. * `Cache::write('cached_data', $data);`
  266. *
  267. * Writing to a specific cache config:
  268. *
  269. * `Cache::write('cached_data', $data, 'long_term');`
  270. *
  271. * @param string $key Identifier for the data
  272. * @param mixed $value Data to be cached - anything except a resource
  273. * @param string $config Optional string configuration name to write to. Defaults to 'default'
  274. * @return bool True if the data was successfully cached, false on failure
  275. */
  276. public static function write($key, $value, $config = 'default') {
  277. $settings = self::settings($config);
  278. if (empty($settings)) {
  279. return false;
  280. }
  281. if (!self::isInitialized($config)) {
  282. return false;
  283. }
  284. $key = self::$_engines[$config]->key($key);
  285. if (!$key || is_resource($value)) {
  286. return false;
  287. }
  288. $success = self::$_engines[$config]->write($settings['prefix'] . $key, $value, $settings['duration']);
  289. self::set(null, $config);
  290. if ($success === false && $value !== '') {
  291. trigger_error(
  292. __d('cake_dev',
  293. "%s cache was unable to write '%s' to %s cache",
  294. $config,
  295. $key,
  296. self::$_engines[$config]->settings['engine']
  297. ),
  298. E_USER_WARNING
  299. );
  300. }
  301. return $success;
  302. }
  303. /**
  304. * Read a key from a cache config.
  305. *
  306. * ### Usage:
  307. *
  308. * Reading from the active cache configuration.
  309. *
  310. * `Cache::read('my_data');`
  311. *
  312. * Reading from a specific cache configuration.
  313. *
  314. * `Cache::read('my_data', 'long_term');`
  315. *
  316. * @param string $key Identifier for the data
  317. * @param string $config optional name of the configuration to use. Defaults to 'default'
  318. * @return mixed The cached data, or false if the data doesn't exist, has expired, or if there was an error fetching it
  319. */
  320. public static function read($key, $config = 'default') {
  321. $settings = self::settings($config);
  322. if (empty($settings)) {
  323. return false;
  324. }
  325. if (!self::isInitialized($config)) {
  326. return false;
  327. }
  328. $key = self::$_engines[$config]->key($key);
  329. if (!$key) {
  330. return false;
  331. }
  332. return self::$_engines[$config]->read($settings['prefix'] . $key);
  333. }
  334. /**
  335. * Increment a number under the key and return incremented value.
  336. *
  337. * @param string $key Identifier for the data
  338. * @param int $offset How much to add
  339. * @param string $config Optional string configuration name. Defaults to 'default'
  340. * @return mixed new value, or false if the data doesn't exist, is not integer,
  341. * or if there was an error fetching it.
  342. */
  343. public static function increment($key, $offset = 1, $config = 'default') {
  344. $settings = self::settings($config);
  345. if (empty($settings)) {
  346. return false;
  347. }
  348. if (!self::isInitialized($config)) {
  349. return false;
  350. }
  351. $key = self::$_engines[$config]->key($key);
  352. if (!$key || !is_int($offset) || $offset < 0) {
  353. return false;
  354. }
  355. $success = self::$_engines[$config]->increment($settings['prefix'] . $key, $offset);
  356. self::set(null, $config);
  357. return $success;
  358. }
  359. /**
  360. * Decrement a number under the key and return decremented value.
  361. *
  362. * @param string $key Identifier for the data
  363. * @param int $offset How much to subtract
  364. * @param string $config Optional string configuration name. Defaults to 'default'
  365. * @return mixed new value, or false if the data doesn't exist, is not integer,
  366. * or if there was an error fetching it
  367. */
  368. public static function decrement($key, $offset = 1, $config = 'default') {
  369. $settings = self::settings($config);
  370. if (empty($settings)) {
  371. return false;
  372. }
  373. if (!self::isInitialized($config)) {
  374. return false;
  375. }
  376. $key = self::$_engines[$config]->key($key);
  377. if (!$key || !is_int($offset) || $offset < 0) {
  378. return false;
  379. }
  380. $success = self::$_engines[$config]->decrement($settings['prefix'] . $key, $offset);
  381. self::set(null, $config);
  382. return $success;
  383. }
  384. /**
  385. * Delete a key from the cache.
  386. *
  387. * ### Usage:
  388. *
  389. * Deleting from the active cache configuration.
  390. *
  391. * `Cache::delete('my_data');`
  392. *
  393. * Deleting from a specific cache configuration.
  394. *
  395. * `Cache::delete('my_data', 'long_term');`
  396. *
  397. * @param string $key Identifier for the data
  398. * @param string $config name of the configuration to use. Defaults to 'default'
  399. * @return bool True if the value was successfully deleted, false if it didn't exist or couldn't be removed
  400. */
  401. public static function delete($key, $config = 'default') {
  402. $settings = self::settings($config);
  403. if (empty($settings)) {
  404. return false;
  405. }
  406. if (!self::isInitialized($config)) {
  407. return false;
  408. }
  409. $key = self::$_engines[$config]->key($key);
  410. if (!$key) {
  411. return false;
  412. }
  413. $success = self::$_engines[$config]->delete($settings['prefix'] . $key);
  414. self::set(null, $config);
  415. return $success;
  416. }
  417. /**
  418. * Delete all keys from the cache.
  419. *
  420. * @param bool $check if true will check expiration, otherwise delete all
  421. * @param string $config name of the configuration to use. Defaults to 'default'
  422. * @return bool True if the cache was successfully cleared, false otherwise
  423. */
  424. public static function clear($check = false, $config = 'default') {
  425. if (!self::isInitialized($config)) {
  426. return false;
  427. }
  428. $success = self::$_engines[$config]->clear($check);
  429. self::set(null, $config);
  430. return $success;
  431. }
  432. /**
  433. * Delete all keys from the cache belonging to the same group.
  434. *
  435. * @param string $group name of the group to be cleared
  436. * @param string $config name of the configuration to use. Defaults to 'default'
  437. * @return bool True if the cache group was successfully cleared, false otherwise
  438. */
  439. public static function clearGroup($group, $config = 'default') {
  440. if (!self::isInitialized($config)) {
  441. return false;
  442. }
  443. $success = self::$_engines[$config]->clearGroup($group);
  444. self::set(null, $config);
  445. return $success;
  446. }
  447. /**
  448. * Check if Cache has initialized a working config for the given name.
  449. *
  450. * @param string $config name of the configuration to use. Defaults to 'default'
  451. * @return bool Whether or not the config name has been initialized.
  452. */
  453. public static function isInitialized($config = 'default') {
  454. if (Configure::read('Cache.disable')) {
  455. return false;
  456. }
  457. return isset(self::$_engines[$config]);
  458. }
  459. /**
  460. * Return the settings for the named cache engine.
  461. *
  462. * @param string $name Name of the configuration to get settings for. Defaults to 'default'
  463. * @return array list of settings for this engine
  464. * @see Cache::config()
  465. */
  466. public static function settings($name = 'default') {
  467. if (!empty(self::$_engines[$name])) {
  468. return self::$_engines[$name]->settings();
  469. }
  470. return array();
  471. }
  472. /**
  473. * Retrieve group names to config mapping.
  474. *
  475. * {{{
  476. * Cache::config('daily', array(
  477. * 'duration' => '1 day', 'groups' => array('posts')
  478. * ));
  479. * Cache::config('weekly', array(
  480. * 'duration' => '1 week', 'groups' => array('posts', 'archive')
  481. * ));
  482. * $configs = Cache::groupConfigs('posts');
  483. * }}}
  484. *
  485. * $config will equal to `array('posts' => array('daily', 'weekly'))`
  486. *
  487. * @param string $group group name or null to retrieve all group mappings
  488. * @return array map of group and all configuration that has the same group
  489. * @throws CacheException
  490. */
  491. public static function groupConfigs($group = null) {
  492. if ($group === null) {
  493. return self::$_groups;
  494. }
  495. if (isset(self::$_groups[$group])) {
  496. return array($group => self::$_groups[$group]);
  497. }
  498. throw new CacheException(__d('cake_dev', 'Invalid cache group %s', $group));
  499. }
  500. /**
  501. * Provides the ability to easily do read-through caching.
  502. *
  503. * When called if the $key is not set in $config, the $callable function
  504. * will be invoked. The results will then be stored into the cache config
  505. * at key.
  506. *
  507. * Examples:
  508. *
  509. * Using a Closure to provide data, assume $this is a Model:
  510. *
  511. * {{{
  512. * $model = $this;
  513. * $results = Cache::remember('all_articles', function() use ($model) {
  514. * return $model->find('all');
  515. * });
  516. * }}}
  517. *
  518. * @param string $key The cache key to read/store data at.
  519. * @param callable $callable The callable that provides data in the case when
  520. * the cache key is empty. Can be any callable type supported by your PHP.
  521. * @param string $config The cache configuration to use for this operation.
  522. * Defaults to default.
  523. * @return mixed The results of the callable or unserialized results.
  524. */
  525. public static function remember($key, $callable, $config = 'default') {
  526. $existing = self::read($key, $config);
  527. if ($existing !== false) {
  528. return $existing;
  529. }
  530. $results = call_user_func($callable);
  531. self::write($key, $results, $config);
  532. return $results;
  533. }
  534. }