Base for a static organization website

Cache.php 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581
  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(static::$_config[$name])) {
  121. $current = static::$_config[$name];
  122. }
  123. if (!empty($settings)) {
  124. static::$_config[$name] = $settings + $current;
  125. }
  126. if (empty(static::$_config[$name]['engine'])) {
  127. return false;
  128. }
  129. if (!empty(static::$_config[$name]['groups'])) {
  130. foreach (static::$_config[$name]['groups'] as $group) {
  131. static::$_groups[$group][] = $name;
  132. sort(static::$_groups[$group]);
  133. static::$_groups[$group] = array_unique(static::$_groups[$group]);
  134. }
  135. }
  136. $engine = static::$_config[$name]['engine'];
  137. if (!isset(static::$_engines[$name])) {
  138. static::_buildEngine($name);
  139. $settings = static::$_config[$name] = static::settings($name);
  140. } elseif ($settings = static::set(static::$_config[$name], null, $name)) {
  141. static::$_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 = static::$_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. static::$_engines[$name] = new $cacheClass();
  165. if (!static::$_engines[$name]->init($config)) {
  166. $msg = __d(
  167. 'cake_dev',
  168. 'Cache engine "%s" is not properly configured. Ensure required extensions are installed, and credentials/permissions are correct',
  169. $name
  170. );
  171. throw new CacheException($msg);
  172. }
  173. if (static::$_engines[$name]->settings['probability'] && time() % static::$_engines[$name]->settings['probability'] === 0) {
  174. static::$_engines[$name]->gc();
  175. }
  176. return true;
  177. }
  178. /**
  179. * Returns an array containing the currently configured Cache settings.
  180. *
  181. * @return array Array of configured Cache config names.
  182. */
  183. public static function configured() {
  184. return array_keys(static::$_config);
  185. }
  186. /**
  187. * Drops a cache engine. Deletes the cache configuration information
  188. * If the deleted configuration is the last configuration using a certain engine,
  189. * the Engine instance is also unset.
  190. *
  191. * @param string $name A currently configured cache config you wish to remove.
  192. * @return bool success of the removal, returns false when the config does not exist.
  193. */
  194. public static function drop($name) {
  195. if (!isset(static::$_config[$name])) {
  196. return false;
  197. }
  198. unset(static::$_config[$name], static::$_engines[$name]);
  199. return true;
  200. }
  201. /**
  202. * Temporarily change the settings on a cache config. The settings will persist for the next write
  203. * operation (write, decrement, increment, clear). Any reads that are done before the write, will
  204. * use the modified settings. If `$settings` is empty, the settings will be reset to the
  205. * original configuration.
  206. *
  207. * Can be called with 2 or 3 parameters. To set multiple values at once.
  208. *
  209. * `Cache::set(array('duration' => '+30 minutes'), 'my_config');`
  210. *
  211. * Or to set one value.
  212. *
  213. * `Cache::set('duration', '+30 minutes', 'my_config');`
  214. *
  215. * To reset a config back to the originally configured values.
  216. *
  217. * `Cache::set(null, 'my_config');`
  218. *
  219. * @param string|array $settings Optional string for simple name-value pair or array
  220. * @param string $value Optional for a simple name-value pair
  221. * @param string $config The configuration name you are changing. Defaults to 'default'
  222. * @return array Array of settings.
  223. */
  224. public static function set($settings = array(), $value = null, $config = 'default') {
  225. if (is_array($settings) && $value !== null) {
  226. $config = $value;
  227. }
  228. if (!isset(static::$_config[$config]) || !isset(static::$_engines[$config])) {
  229. return false;
  230. }
  231. if (!empty($settings)) {
  232. static::$_reset = true;
  233. }
  234. if (static::$_reset === true) {
  235. if (empty($settings)) {
  236. static::$_reset = false;
  237. $settings = static::$_config[$config];
  238. } else {
  239. if (is_string($settings) && $value !== null) {
  240. $settings = array($settings => $value);
  241. }
  242. $settings += static::$_config[$config];
  243. if (isset($settings['duration']) && !is_numeric($settings['duration'])) {
  244. $settings['duration'] = strtotime($settings['duration']) - time();
  245. }
  246. }
  247. static::$_engines[$config]->settings = $settings;
  248. }
  249. return static::settings($config);
  250. }
  251. /**
  252. * Garbage collection
  253. *
  254. * Permanently remove all expired and deleted data
  255. *
  256. * @param string $config [optional] The config name you wish to have garbage collected. Defaults to 'default'
  257. * @param int $expires [optional] An expires timestamp. Defaults to NULL
  258. * @return void
  259. */
  260. public static function gc($config = 'default', $expires = null) {
  261. static::$_engines[$config]->gc($expires);
  262. }
  263. /**
  264. * Write data for key into a cache engine.
  265. *
  266. * ### Usage:
  267. *
  268. * Writing to the active cache config:
  269. *
  270. * `Cache::write('cached_data', $data);`
  271. *
  272. * Writing to a specific cache config:
  273. *
  274. * `Cache::write('cached_data', $data, 'long_term');`
  275. *
  276. * @param string $key Identifier for the data
  277. * @param mixed $value Data to be cached - anything except a resource
  278. * @param string $config Optional string configuration name to write to. Defaults to 'default'
  279. * @return bool True if the data was successfully cached, false on failure
  280. */
  281. public static function write($key, $value, $config = 'default') {
  282. $settings = static::settings($config);
  283. if (empty($settings)) {
  284. return false;
  285. }
  286. if (!static::isInitialized($config)) {
  287. return false;
  288. }
  289. $key = static::$_engines[$config]->key($key);
  290. if (!$key || is_resource($value)) {
  291. return false;
  292. }
  293. $success = static::$_engines[$config]->write($settings['prefix'] . $key, $value, $settings['duration']);
  294. static::set(null, $config);
  295. if ($success === false && $value !== '') {
  296. trigger_error(
  297. __d('cake_dev',
  298. "%s cache was unable to write '%s' to %s cache",
  299. $config,
  300. $key,
  301. static::$_engines[$config]->settings['engine']
  302. ),
  303. E_USER_WARNING
  304. );
  305. }
  306. return $success;
  307. }
  308. /**
  309. * Read a key from a cache config.
  310. *
  311. * ### Usage:
  312. *
  313. * Reading from the active cache configuration.
  314. *
  315. * `Cache::read('my_data');`
  316. *
  317. * Reading from a specific cache configuration.
  318. *
  319. * `Cache::read('my_data', 'long_term');`
  320. *
  321. * @param string $key Identifier for the data
  322. * @param string $config optional name of the configuration to use. Defaults to 'default'
  323. * @return mixed The cached data, or false if the data doesn't exist, has expired, or if there was an error fetching it
  324. */
  325. public static function read($key, $config = 'default') {
  326. $settings = static::settings($config);
  327. if (empty($settings)) {
  328. return false;
  329. }
  330. if (!static::isInitialized($config)) {
  331. return false;
  332. }
  333. $key = static::$_engines[$config]->key($key);
  334. if (!$key) {
  335. return false;
  336. }
  337. return static::$_engines[$config]->read($settings['prefix'] . $key);
  338. }
  339. /**
  340. * Increment a number under the key and return incremented value.
  341. *
  342. * @param string $key Identifier for the data
  343. * @param int $offset How much to add
  344. * @param string $config Optional string configuration name. Defaults to 'default'
  345. * @return mixed new value, or false if the data doesn't exist, is not integer,
  346. * or if there was an error fetching it.
  347. */
  348. public static function increment($key, $offset = 1, $config = 'default') {
  349. $settings = static::settings($config);
  350. if (empty($settings)) {
  351. return false;
  352. }
  353. if (!static::isInitialized($config)) {
  354. return false;
  355. }
  356. $key = static::$_engines[$config]->key($key);
  357. if (!$key || !is_int($offset) || $offset < 0) {
  358. return false;
  359. }
  360. $success = static::$_engines[$config]->increment($settings['prefix'] . $key, $offset);
  361. static::set(null, $config);
  362. return $success;
  363. }
  364. /**
  365. * Decrement a number under the key and return decremented value.
  366. *
  367. * @param string $key Identifier for the data
  368. * @param int $offset How much to subtract
  369. * @param string $config Optional string configuration name. Defaults to 'default'
  370. * @return mixed new value, or false if the data doesn't exist, is not integer,
  371. * or if there was an error fetching it
  372. */
  373. public static function decrement($key, $offset = 1, $config = 'default') {
  374. $settings = static::settings($config);
  375. if (empty($settings)) {
  376. return false;
  377. }
  378. if (!static::isInitialized($config)) {
  379. return false;
  380. }
  381. $key = static::$_engines[$config]->key($key);
  382. if (!$key || !is_int($offset) || $offset < 0) {
  383. return false;
  384. }
  385. $success = static::$_engines[$config]->decrement($settings['prefix'] . $key, $offset);
  386. static::set(null, $config);
  387. return $success;
  388. }
  389. /**
  390. * Delete a key from the cache.
  391. *
  392. * ### Usage:
  393. *
  394. * Deleting from the active cache configuration.
  395. *
  396. * `Cache::delete('my_data');`
  397. *
  398. * Deleting from a specific cache configuration.
  399. *
  400. * `Cache::delete('my_data', 'long_term');`
  401. *
  402. * @param string $key Identifier for the data
  403. * @param string $config name of the configuration to use. Defaults to 'default'
  404. * @return bool True if the value was successfully deleted, false if it didn't exist or couldn't be removed
  405. */
  406. public static function delete($key, $config = 'default') {
  407. $settings = static::settings($config);
  408. if (empty($settings)) {
  409. return false;
  410. }
  411. if (!static::isInitialized($config)) {
  412. return false;
  413. }
  414. $key = static::$_engines[$config]->key($key);
  415. if (!$key) {
  416. return false;
  417. }
  418. $success = static::$_engines[$config]->delete($settings['prefix'] . $key);
  419. static::set(null, $config);
  420. return $success;
  421. }
  422. /**
  423. * Delete all keys from the cache.
  424. *
  425. * @param bool $check if true will check expiration, otherwise delete all
  426. * @param string $config name of the configuration to use. Defaults to 'default'
  427. * @return bool True if the cache was successfully cleared, false otherwise
  428. */
  429. public static function clear($check = false, $config = 'default') {
  430. if (!static::isInitialized($config)) {
  431. return false;
  432. }
  433. $success = static::$_engines[$config]->clear($check);
  434. static::set(null, $config);
  435. return $success;
  436. }
  437. /**
  438. * Delete all keys from the cache belonging to the same group.
  439. *
  440. * @param string $group name of the group to be cleared
  441. * @param string $config name of the configuration to use. Defaults to 'default'
  442. * @return bool True if the cache group was successfully cleared, false otherwise
  443. */
  444. public static function clearGroup($group, $config = 'default') {
  445. if (!static::isInitialized($config)) {
  446. return false;
  447. }
  448. $success = static::$_engines[$config]->clearGroup($group);
  449. static::set(null, $config);
  450. return $success;
  451. }
  452. /**
  453. * Check if Cache has initialized a working config for the given name.
  454. *
  455. * @param string $config name of the configuration to use. Defaults to 'default'
  456. * @return bool Whether or not the config name has been initialized.
  457. */
  458. public static function isInitialized($config = 'default') {
  459. if (Configure::read('Cache.disable')) {
  460. return false;
  461. }
  462. return isset(static::$_engines[$config]);
  463. }
  464. /**
  465. * Return the settings for the named cache engine.
  466. *
  467. * @param string $name Name of the configuration to get settings for. Defaults to 'default'
  468. * @return array list of settings for this engine
  469. * @see Cache::config()
  470. */
  471. public static function settings($name = 'default') {
  472. if (!empty(static::$_engines[$name])) {
  473. return static::$_engines[$name]->settings();
  474. }
  475. return array();
  476. }
  477. /**
  478. * Retrieve group names to config mapping.
  479. *
  480. * ```
  481. * Cache::config('daily', array(
  482. * 'duration' => '1 day', 'groups' => array('posts')
  483. * ));
  484. * Cache::config('weekly', array(
  485. * 'duration' => '1 week', 'groups' => array('posts', 'archive')
  486. * ));
  487. * $configs = Cache::groupConfigs('posts');
  488. * ```
  489. *
  490. * $config will equal to `array('posts' => array('daily', 'weekly'))`
  491. *
  492. * @param string $group group name or null to retrieve all group mappings
  493. * @return array map of group and all configuration that has the same group
  494. * @throws CacheException
  495. */
  496. public static function groupConfigs($group = null) {
  497. if ($group === null) {
  498. return static::$_groups;
  499. }
  500. if (isset(static::$_groups[$group])) {
  501. return array($group => static::$_groups[$group]);
  502. }
  503. throw new CacheException(__d('cake_dev', 'Invalid cache group %s', $group));
  504. }
  505. /**
  506. * Provides the ability to easily do read-through caching.
  507. *
  508. * When called if the $key is not set in $config, the $callable function
  509. * will be invoked. The results will then be stored into the cache config
  510. * at key.
  511. *
  512. * Examples:
  513. *
  514. * Using a Closure to provide data, assume $this is a Model:
  515. *
  516. * ```
  517. * $model = $this;
  518. * $results = Cache::remember('all_articles', function() use ($model) {
  519. * return $model->find('all');
  520. * });
  521. * ```
  522. *
  523. * @param string $key The cache key to read/store data at.
  524. * @param callable $callable The callable that provides data in the case when
  525. * the cache key is empty. Can be any callable type supported by your PHP.
  526. * @param string $config The cache configuration to use for this operation.
  527. * Defaults to default.
  528. * @return mixed The results of the callable or unserialized results.
  529. */
  530. public static function remember($key, $callable, $config = 'default') {
  531. $existing = static::read($key, $config);
  532. if ($existing !== false) {
  533. return $existing;
  534. }
  535. $results = call_user_func($callable);
  536. static::write($key, $results, $config);
  537. return $results;
  538. }
  539. }