Cache.php 14 KB

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