Cache.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  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. * - `prefix` Prefix appended to all entries. Good for when you need to share a keyspace
  89. * with either another cache config or another application.
  90. * - `probability` Probability of hitting a cache gc cleanup. Setting to 0 will disable
  91. * cache::gc from ever being called automatically.
  92. * - `servers' Used by memcache. Give the address of the memcached servers to use.
  93. * - `compress` Used by memcache. Enables memcache's compressed format.
  94. * - `serialize` Used by FileCache. Should cache objects be serialized first.
  95. * - `path` Used by FileCache. Path to where cachefiles should be saved.
  96. * - `lock` Used by FileCache. Should files be locked before writing to them?
  97. * - `user` Used by Xcache. Username for XCache
  98. * - `password` Used by Xcache. Password for XCache
  99. *
  100. * @see app/Config/core.php for configuration settings
  101. * @param string $name Name of the configuration
  102. * @param array $settings Optional associative array of settings passed to the engine
  103. * @return array(engine, settings) on success, false on failure
  104. * @throws CacheException
  105. */
  106. public static function config($name = null, $settings = array()) {
  107. if (is_array($name)) {
  108. $settings = $name;
  109. }
  110. $current = array();
  111. if (isset(self::$_config[$name])) {
  112. $current = self::$_config[$name];
  113. }
  114. if (!empty($settings)) {
  115. self::$_config[$name] = array_merge($current, $settings);
  116. }
  117. if (empty(self::$_config[$name]['engine'])) {
  118. return false;
  119. }
  120. $engine = self::$_config[$name]['engine'];
  121. if (!isset(self::$_engines[$name])) {
  122. self::_buildEngine($name);
  123. $settings = self::$_config[$name] = self::settings($name);
  124. } elseif ($settings = self::set(self::$_config[$name], null, $name)) {
  125. self::$_config[$name] = $settings;
  126. }
  127. return compact('engine', 'settings');
  128. }
  129. /**
  130. * Finds and builds the instance of the required engine class.
  131. *
  132. * @param string $name Name of the config array that needs an engine instance built
  133. * @return boolean
  134. * @throws CacheException
  135. */
  136. protected static function _buildEngine($name) {
  137. $config = self::$_config[$name];
  138. list($plugin, $class) = pluginSplit($config['engine'], true);
  139. $cacheClass = $class . 'Engine';
  140. App::uses($cacheClass, $plugin . 'Cache/Engine');
  141. if (!class_exists($cacheClass)) {
  142. return false;
  143. }
  144. $cacheClass = $class . 'Engine';
  145. if (!is_subclass_of($cacheClass, 'CacheEngine')) {
  146. throw new CacheException(__d('cake_dev', 'Cache engines must use CacheEngine as a base class.'));
  147. }
  148. self::$_engines[$name] = new $cacheClass();
  149. if (self::$_engines[$name]->init($config)) {
  150. if (self::$_engines[$name]->settings['probability'] && time() % self::$_engines[$name]->settings['probability'] === 0) {
  151. self::$_engines[$name]->gc();
  152. }
  153. return true;
  154. }
  155. return false;
  156. }
  157. /**
  158. * Returns an array containing the currently configured Cache settings.
  159. *
  160. * @return array Array of configured Cache config names.
  161. */
  162. public static function configured() {
  163. return array_keys(self::$_config);
  164. }
  165. /**
  166. * Drops a cache engine. Deletes the cache configuration information
  167. * If the deleted configuration is the last configuration using an certain engine,
  168. * the Engine instance is also unset.
  169. *
  170. * @param string $name A currently configured cache config you wish to remove.
  171. * @return boolean success of the removal, returns false when the config does not exist.
  172. */
  173. public static function drop($name) {
  174. if (!isset(self::$_config[$name])) {
  175. return false;
  176. }
  177. unset(self::$_config[$name], self::$_engines[$name]);
  178. return true;
  179. }
  180. /**
  181. * Temporarily change the settings on a cache config. The settings will persist for the next write
  182. * operation (write, decrement, increment, clear). Any reads that are done before the write, will
  183. * use the modified settings. If `$settings` is empty, the settings will be reset to the
  184. * original configuration.
  185. *
  186. * Can be called with 2 or 3 parameters. To set multiple values at once.
  187. *
  188. * `Cache::set(array('duration' => '+30 minutes'), 'my_config');`
  189. *
  190. * Or to set one value.
  191. *
  192. * `Cache::set('duration', '+30 minutes', 'my_config');`
  193. *
  194. * To reset a config back to the originally configured values.
  195. *
  196. * `Cache::set(null, 'my_config');`
  197. *
  198. * @param mixed $settings Optional string for simple name-value pair or array
  199. * @param string $value Optional for a simple name-value pair
  200. * @param string $config The configuration name you are changing. Defaults to 'default'
  201. * @return array Array of settings.
  202. */
  203. public static function set($settings = array(), $value = null, $config = 'default') {
  204. if (is_array($settings) && $value !== null) {
  205. $config = $value;
  206. }
  207. if (!isset(self::$_config[$config]) || !isset(self::$_engines[$config])) {
  208. return false;
  209. }
  210. if (!empty($settings)) {
  211. self::$_reset = true;
  212. }
  213. if (self::$_reset === true) {
  214. if (empty($settings)) {
  215. self::$_reset = false;
  216. $settings = self::$_config[$config];
  217. } else {
  218. if (is_string($settings) && $value !== null) {
  219. $settings = array($settings => $value);
  220. }
  221. $settings = array_merge(self::$_config[$config], $settings);
  222. if (isset($settings['duration']) && !is_numeric($settings['duration'])) {
  223. $settings['duration'] = strtotime($settings['duration']) - time();
  224. }
  225. }
  226. self::$_engines[$config]->settings = $settings;
  227. }
  228. return self::settings($config);
  229. }
  230. /**
  231. * Garbage collection
  232. *
  233. * Permanently remove all expired and deleted data
  234. *
  235. * @param string $config [optional] The config name you wish to have garbage collected. Defaults to 'default'
  236. * @param integer $expires [optional] An expires timestamp. Defaults to NULL
  237. * @return void
  238. */
  239. public static function gc($config = 'default', $expires = null) {
  240. self::$_engines[$config]->gc($expires);
  241. }
  242. /**
  243. * Write data for key into cache. Will automatically use the currently
  244. * active cache configuration. To set the currently active configuration use
  245. * Cache::config()
  246. *
  247. * ### Usage:
  248. *
  249. * Writing to the active cache config:
  250. *
  251. * `Cache::write('cached_data', $data);`
  252. *
  253. * Writing to a specific cache config:
  254. *
  255. * `Cache::write('cached_data', $data, 'long_term');`
  256. *
  257. * @param string $key Identifier for the data
  258. * @param mixed $value Data to be cached - anything except a resource
  259. * @param string $config Optional string configuration name to write to. Defaults to 'default'
  260. * @return boolean True if the data was successfully cached, false on failure
  261. */
  262. public static function write($key, $value, $config = 'default') {
  263. $settings = self::settings($config);
  264. if (empty($settings)) {
  265. return false;
  266. }
  267. if (!self::isInitialized($config)) {
  268. return false;
  269. }
  270. $key = self::$_engines[$config]->key($key);
  271. if (!$key || is_resource($value)) {
  272. return false;
  273. }
  274. $success = self::$_engines[$config]->write($settings['prefix'] . $key, $value, $settings['duration']);
  275. self::set(null, $config);
  276. if ($success === false && $value !== '') {
  277. trigger_error(
  278. __d('cake_dev',
  279. "%s cache was unable to write '%s' to %s cache",
  280. $config,
  281. $key,
  282. self::$_engines[$config]->settings['engine']
  283. ),
  284. E_USER_WARNING
  285. );
  286. }
  287. return $success;
  288. }
  289. /**
  290. * Read a key from the cache. Will automatically use the currently
  291. * active cache configuration. To set the currently active configuration use
  292. * Cache::config()
  293. *
  294. * ### Usage:
  295. *
  296. * Reading from the active cache configuration.
  297. *
  298. * `Cache::read('my_data');`
  299. *
  300. * Reading from a specific cache configuration.
  301. *
  302. * `Cache::read('my_data', 'long_term');`
  303. *
  304. * @param string $key Identifier for the data
  305. * @param string $config optional name of the configuration to use. Defaults to 'default'
  306. * @return mixed The cached data, or false if the data doesn't exist, has expired, or if there was an error fetching it
  307. */
  308. public static function read($key, $config = 'default') {
  309. $settings = self::settings($config);
  310. if (empty($settings)) {
  311. return false;
  312. }
  313. if (!self::isInitialized($config)) {
  314. return false;
  315. }
  316. $key = self::$_engines[$config]->key($key);
  317. if (!$key) {
  318. return false;
  319. }
  320. return self::$_engines[$config]->read($settings['prefix'] . $key);
  321. }
  322. /**
  323. * Increment a number under the key and return incremented value.
  324. *
  325. * @param string $key Identifier for the data
  326. * @param integer $offset How much to add
  327. * @param string $config Optional string configuration name. Defaults to 'default'
  328. * @return mixed new value, or false if the data doesn't exist, is not integer,
  329. * or if there was an error fetching it.
  330. */
  331. public static function increment($key, $offset = 1, $config = 'default') {
  332. $settings = self::settings($config);
  333. if (empty($settings)) {
  334. return false;
  335. }
  336. if (!self::isInitialized($config)) {
  337. return false;
  338. }
  339. $key = self::$_engines[$config]->key($key);
  340. if (!$key || !is_integer($offset) || $offset < 0) {
  341. return false;
  342. }
  343. $success = self::$_engines[$config]->increment($settings['prefix'] . $key, $offset);
  344. self::set(null, $config);
  345. return $success;
  346. }
  347. /**
  348. * Decrement a number under the key and return decremented value.
  349. *
  350. * @param string $key Identifier for the data
  351. * @param integer $offset How much to subtract
  352. * @param string $config Optional string configuration name. Defaults to 'default'
  353. * @return mixed new value, or false if the data doesn't exist, is not integer,
  354. * or if there was an error fetching it
  355. */
  356. public static function decrement($key, $offset = 1, $config = 'default') {
  357. $settings = self::settings($config);
  358. if (empty($settings)) {
  359. return false;
  360. }
  361. if (!self::isInitialized($config)) {
  362. return false;
  363. }
  364. $key = self::$_engines[$config]->key($key);
  365. if (!$key || !is_integer($offset) || $offset < 0) {
  366. return false;
  367. }
  368. $success = self::$_engines[$config]->decrement($settings['prefix'] . $key, $offset);
  369. self::set(null, $config);
  370. return $success;
  371. }
  372. /**
  373. * Delete a key from the cache.
  374. *
  375. * ### Usage:
  376. *
  377. * Deleting from the active cache configuration.
  378. *
  379. * `Cache::delete('my_data');`
  380. *
  381. * Deleting from a specific cache configuration.
  382. *
  383. * `Cache::delete('my_data', 'long_term');`
  384. *
  385. * @param string $key Identifier for the data
  386. * @param string $config name of the configuration to use. Defaults to 'default'
  387. * @return boolean True if the value was successfully deleted, false if it didn't exist or couldn't be removed
  388. */
  389. public static function delete($key, $config = 'default') {
  390. $settings = self::settings($config);
  391. if (empty($settings)) {
  392. return false;
  393. }
  394. if (!self::isInitialized($config)) {
  395. return false;
  396. }
  397. $key = self::$_engines[$config]->key($key);
  398. if (!$key) {
  399. return false;
  400. }
  401. $success = self::$_engines[$config]->delete($settings['prefix'] . $key);
  402. self::set(null, $config);
  403. return $success;
  404. }
  405. /**
  406. * Delete all keys from the cache.
  407. *
  408. * @param boolean $check if true will check expiration, otherwise delete all
  409. * @param string $config name of the configuration to use. Defaults to 'default'
  410. * @return boolean True if the cache was successfully cleared, false otherwise
  411. */
  412. public static function clear($check = false, $config = 'default') {
  413. if (!self::isInitialized($config)) {
  414. return false;
  415. }
  416. $success = self::$_engines[$config]->clear($check);
  417. self::set(null, $config);
  418. return $success;
  419. }
  420. /**
  421. * Check if Cache has initialized a working config for the given name.
  422. *
  423. * @param string $config name of the configuration to use. Defaults to 'default'
  424. * @return boolean Whether or not the config name has been initialized.
  425. */
  426. public static function isInitialized($config = 'default') {
  427. if (Configure::read('Cache.disable')) {
  428. return false;
  429. }
  430. return isset(self::$_engines[$config]);
  431. }
  432. /**
  433. * Return the settings for the named cache engine.
  434. *
  435. * @param string $name Name of the configuration to get settings for. Defaults to 'default'
  436. * @return array list of settings for this engine
  437. * @see Cache::config()
  438. */
  439. public static function settings($name = 'default') {
  440. if (!empty(self::$_engines[$name])) {
  441. return self::$_engines[$name]->settings();
  442. }
  443. return array();
  444. }
  445. }