Skip navigation
Help

cache.inc

  1. drupal
    1. 6 drupal/includes/cache.inc
    2. 7 drupal/includes/cache.inc

Functions & methods

NameDescription
cache_clear_allExpire data from the cache.
cache_getReturn data from the persistent cache
cache_get_multipleReturn data from the persistent cache when given an array of cache IDs.
cache_is_emptyCheck if a cache bin is empty.
cache_setStore data in the persistent cache.
_cache_get_objectGet the cache object for a cache bin.

Interfaces

NameDescription
DrupalCacheInterfaceInterface for cache implementations.

Classes

NameDescription
DrupalDatabaseCacheDefault cache implementation.

File

drupal/includes/cache.inc
View source
  1. <?php
  2. /**
  3. * Get the cache object for a cache bin.
  4. *
  5. * By default, this returns an instance of the DrupalDatabaseCache class.
  6. * Classes implementing DrupalCacheInterface can register themselves both as a
  7. * default implementation and for specific bins.
  8. *
  9. * @see DrupalCacheInterface
  10. *
  11. * @param $bin
  12. * The cache bin for which the cache object should be returned.
  13. * @return DrupalCacheInterface
  14. * The cache object associated with the specified bin.
  15. */
  16. function _cache_get_object($bin) {
  17. // We do not use drupal_static() here because we do not want to change the
  18. // storage of a cache bin mid-request.
  19. static $cache_objects;
  20. if (!isset($cache_objects[$bin])) {
  21. $class = variable_get('cache_class_' . $bin);
  22. if (!isset($class)) {
  23. $class = variable_get('cache_default_class', 'DrupalDatabaseCache');
  24. }
  25. $cache_objects[$bin] = new $class($bin);
  26. }
  27. return $cache_objects[$bin];
  28. }
  29. /**
  30. * Return data from the persistent cache
  31. *
  32. * Data may be stored as either plain text or as serialized data. cache_get
  33. * will automatically return unserialized objects and arrays.
  34. *
  35. * @param $cid
  36. * The cache ID of the data to retrieve.
  37. * @param $bin
  38. * The cache bin to store the data in. Valid core values are 'cache_block',
  39. * 'cache_bootstrap', 'cache_field', 'cache_filter', 'cache_form',
  40. * 'cache_menu', 'cache_page', 'cache_path', 'cache_update' or 'cache' for
  41. * the default cache.
  42. *
  43. * @return
  44. * The cache or FALSE on failure.
  45. */
  46. function cache_get($cid, $bin = 'cache') {
  47. return _cache_get_object($bin)->get($cid);
  48. }
  49. /**
  50. * Return data from the persistent cache when given an array of cache IDs.
  51. *
  52. * @param $cids
  53. * An array of cache IDs for the data to retrieve. This is passed by
  54. * reference, and will have the IDs successfully returned from cache removed.
  55. * @param $bin
  56. * The cache bin where the data is stored.
  57. * @return
  58. * An array of the items successfully returned from cache indexed by cid.
  59. */
  60. function cache_get_multiple(array &$cids, $bin = 'cache') {
  61. return _cache_get_object($bin)->getMultiple($cids);
  62. }
  63. /**
  64. * Store data in the persistent cache.
  65. *
  66. * The persistent cache is split up into several cache bins. In the default
  67. * cache implementation, each cache bin corresponds to a database table by the
  68. * same name. Other implementations might want to store several bins in data
  69. * structures that get flushed together. While it is not a problem for most
  70. * cache bins if the entries in them are flushed before their expire time, some
  71. * might break functionality or are extremely expensive to recalculate. These
  72. * will be marked with a (*). The other bins expired automatically by core.
  73. * Contributed modules can add additional bins and get them expired
  74. * automatically by implementing hook_flush_caches().
  75. *
  76. * - cache: Generic cache storage bin (used for variables, theme registry,
  77. * locale date, list of simpletest tests etc).
  78. *
  79. * - cache_block: Stores the content of various blocks.
  80. *
  81. * - cache field: Stores the field data belonging to a given object.
  82. *
  83. * - cache_filter: Stores filtered pieces of content.
  84. *
  85. * - cache_form(*): Stores multistep forms. Flushing this bin means that some
  86. * forms displayed to users lose their state and the data already submitted
  87. * to them.
  88. *
  89. * - cache_menu: Stores the structure of visible navigation menus per page.
  90. *
  91. * - cache_page: Stores generated pages for anonymous users. It is flushed
  92. * very often, whenever a page changes, at least for every ode and comment
  93. * submission. This is the only bin affected by the page cache setting on
  94. * the administrator panel.
  95. *
  96. * - cache path: Stores the system paths that have an alias.
  97. *
  98. * - cache update(*): Stores available releases. The update server (for
  99. * example, drupal.org) needs to produce the relevant XML for every project
  100. * installed on the current site. As this is different for (almost) every
  101. * site, it's very expensive to recalculate for the update server.
  102. *
  103. * The reasons for having several bins are as follows:
  104. *
  105. * - smaller bins mean smaller database tables and allow for faster selects and
  106. * inserts
  107. * - we try to put fast changing cache items and rather static ones into
  108. * different bins. The effect is that only the fast changing bins will need a
  109. * lot of writes to disk. The more static bins will also be better cacheable
  110. * with MySQL's query cache.
  111. *
  112. * @param $cid
  113. * The cache ID of the data to store.
  114. * @param $data
  115. * The data to store in the cache. Complex data types will be automatically
  116. * serialized before insertion.
  117. * Strings will be stored as plain text and not serialized.
  118. * @param $bin
  119. * The cache bin to store the data in. Valid core values are 'cache_block',
  120. * 'cache_bootstrap', 'cache_field', 'cache_filter', 'cache_form',
  121. * 'cache_menu', 'cache_page', 'cache_update' or 'cache' for the default
  122. * cache.
  123. * @param $expire
  124. * One of the following values:
  125. * - CACHE_PERMANENT: Indicates that the item should never be removed unless
  126. * explicitly told to using cache_clear_all() with a cache ID.
  127. * - CACHE_TEMPORARY: Indicates that the item should be removed at the next
  128. * general cache wipe.
  129. * - A Unix timestamp: Indicates that the item should be kept at least until
  130. * the given time, after which it behaves like CACHE_TEMPORARY.
  131. */
  132. function cache_set($cid, $data, $bin = 'cache', $expire = CACHE_PERMANENT) {
  133. return _cache_get_object($bin)->set($cid, $data, $expire);
  134. }
  135. /**
  136. * Expire data from the cache.
  137. *
  138. * If called without arguments, expirable entries will be cleared from the
  139. * cache_page and cache_block bins.
  140. *
  141. * @param $cid
  142. * If set, the cache ID to delete. Otherwise, all cache entries that can
  143. * expire are deleted.
  144. *
  145. * @param $bin
  146. * If set, the bin $bin to delete from. Mandatory
  147. * argument if $cid is set.
  148. *
  149. * @param $wildcard
  150. * If $wildcard is TRUE, cache IDs starting with $cid are deleted in
  151. * addition to the exact cache ID specified by $cid. If $wildcard is
  152. * TRUE and $cid is '*' then the entire bin $bin is emptied.
  153. */
  154. function cache_clear_all($cid = NULL, $bin = NULL, $wildcard = FALSE) {
  155. if (!isset($cid) && !isset($bin)) {
  156. // Clear the block cache first, so stale data will
  157. // not end up in the page cache.
  158. if (module_exists('block')) {
  159. cache_clear_all(NULL, 'cache_block');
  160. }
  161. cache_clear_all(NULL, 'cache_page');
  162. return;
  163. }
  164. return _cache_get_object($bin)->clear($cid, $wildcard);
  165. }
  166. /**
  167. * Check if a cache bin is empty.
  168. *
  169. * A cache bin is considered empty if it does not contain any valid data for any
  170. * cache ID.
  171. *
  172. * @param $bin
  173. * The cache bin to check.
  174. * @return
  175. * TRUE if the cache bin specified is empty.
  176. */
  177. function cache_is_empty($bin) {
  178. return _cache_get_object($bin)->isEmpty();
  179. }
  180. /**
  181. * Interface for cache implementations.
  182. *
  183. * All cache implementations have to implement this interface.
  184. * DrupalDatabaseCache provides the default implementation, which can be
  185. * consulted as an example.
  186. *
  187. * To make Drupal use your implementation for a certain cache bin, you have to
  188. * set a variable with the name of the cache bin as its key and the name of
  189. * your class as its value. For example, if your implementation of
  190. * DrupalCacheInterface was called MyCustomCache, the following line would make
  191. * Drupal use it for the 'cache_page' bin:
  192. * @code
  193. * variable_set('cache_class_cache_page', 'MyCustomCache');
  194. * @endcode
  195. *
  196. * Additionally, you can register your cache implementation to be used by
  197. * default for all cache bins by setting the variable 'cache_default_class' to
  198. * the name of your implementation of the DrupalCacheInterface, e.g.
  199. * @code
  200. * variable_set('cache_default_class', 'MyCustomCache');
  201. * @endcode
  202. *
  203. * To implement a completely custom cache bin, use the same variable format:
  204. * @code
  205. * variable_set('cache_class_custom_bin', 'MyCustomCache');
  206. * @endcode
  207. * To access your custom cache bin, specify the name of the bin when storing
  208. * or retrieving cached data:
  209. * @code
  210. * cache_set($cid, $data, 'custom_bin', $expire);
  211. * cache_get($cid, 'custom_bin');
  212. * @endcode
  213. *
  214. * @see _cache_get_object()
  215. * @see DrupalDatabaseCache
  216. */
  217. interface DrupalCacheInterface {
  218. /**
  219. * Constructor.
  220. *
  221. * @param $bin
  222. * The cache bin for which the object is created.
  223. */
  224. function __construct($bin);
  225. /**
  226. * Return data from the persistent cache. Data may be stored as either plain
  227. * text or as serialized data. cache_get will automatically return
  228. * unserialized objects and arrays.
  229. *
  230. * @param $cid
  231. * The cache ID of the data to retrieve.
  232. * @return
  233. * The cache or FALSE on failure.
  234. */
  235. function get($cid);
  236. /**
  237. * Return data from the persistent cache when given an array of cache IDs.
  238. *
  239. * @param $cids
  240. * An array of cache IDs for the data to retrieve. This is passed by
  241. * reference, and will have the IDs successfully returned from cache
  242. * removed.
  243. * @return
  244. * An array of the items successfully returned from cache indexed by cid.
  245. */
  246. function getMultiple(&$cids);
  247. /**
  248. * Store data in the persistent cache.
  249. *
  250. * @param $cid
  251. * The cache ID of the data to store.
  252. * @param $data
  253. * The data to store in the cache. Complex data types will be automatically
  254. * serialized before insertion.
  255. * Strings will be stored as plain text and not serialized.
  256. * @param $expire
  257. * One of the following values:
  258. * - CACHE_PERMANENT: Indicates that the item should never be removed unless
  259. * explicitly told to using cache_clear_all() with a cache ID.
  260. * - CACHE_TEMPORARY: Indicates that the item should be removed at the next
  261. * general cache wipe.
  262. * - A Unix timestamp: Indicates that the item should be kept at least until
  263. * the given time, after which it behaves like CACHE_TEMPORARY.
  264. */
  265. function set($cid, $data, $expire = CACHE_PERMANENT);
  266. /**
  267. * Expire data from the cache. If called without arguments, expirable
  268. * entries will be cleared from the cache_page and cache_block bins.
  269. *
  270. * @param $cid
  271. * If set, the cache ID to delete. Otherwise, all cache entries that can
  272. * expire are deleted.
  273. * @param $wildcard
  274. * If set to TRUE, the $cid is treated as a substring
  275. * to match rather than a complete ID. The match is a right hand
  276. * match. If '*' is given as $cid, the bin $bin will be emptied.
  277. */
  278. function clear($cid = NULL, $wildcard = FALSE);
  279. /**
  280. * Check if a cache bin is empty.
  281. *
  282. * A cache bin is considered empty if it does not contain any valid data for
  283. * any cache ID.
  284. *
  285. * @return
  286. * TRUE if the cache bin specified is empty.
  287. */
  288. function isEmpty();
  289. }
  290. /**
  291. * Default cache implementation.
  292. *
  293. * This is Drupal's default cache implementation. It uses the database to store
  294. * cached data. Each cache bin corresponds to a database table by the same name.
  295. */
  296. class DrupalDatabaseCache implements DrupalCacheInterface {
  297. protected $bin;
  298. function __construct($bin) {
  299. $this->bin = $bin;
  300. }
  301. function get($cid) {
  302. $cids = array($cid);
  303. $cache = $this->getMultiple($cids);
  304. return reset($cache);
  305. }
  306. function getMultiple(&$cids) {
  307. try {
  308. // Garbage collection necessary when enforcing a minimum cache lifetime.
  309. $this->garbageCollection($this->bin);
  310. // When serving cached pages, the overhead of using db_select() was found
  311. // to add around 30% overhead to the request. Since $this->bin is a
  312. // variable, this means the call to db_query() here uses a concatenated
  313. // string. This is highly discouraged under any other circumstances, and
  314. // is used here only due to the performance overhead we would incur
  315. // otherwise. When serving an uncached page, the overhead of using
  316. // db_select() is a much smaller proportion of the request.
  317. $result = db_query('SELECT cid, data, created, expire, serialized FROM {' . db_escape_table($this->bin) . '} WHERE cid IN (:cids)', array(':cids' => $cids));
  318. $cache = array();
  319. foreach ($result as $item) {
  320. $item = $this->prepareItem($item);
  321. if ($item) {
  322. $cache[$item->cid] = $item;
  323. }
  324. }
  325. $cids = array_diff($cids, array_keys($cache));
  326. return $cache;
  327. }
  328. catch (Exception $e) {
  329. // If the database is never going to be available, cache requests should
  330. // return FALSE in order to allow exception handling to occur.
  331. return array();
  332. }
  333. }
  334. /**
  335. * Garbage collection for get() and getMultiple().
  336. *
  337. * @param $bin
  338. * The bin being requested.
  339. */
  340. protected function garbageCollection() {
  341. global $user;
  342. // Garbage collection necessary when enforcing a minimum cache lifetime.
  343. $cache_flush = variable_get('cache_flush_' . $this->bin, 0);
  344. if ($cache_flush && ($cache_flush + variable_get('cache_lifetime', 0) <= REQUEST_TIME)) {
  345. // Reset the variable immediately to prevent a meltdown in heavy load situations.
  346. variable_set('cache_flush_' . $this->bin, 0);
  347. // Time to flush old cache data
  348. db_delete($this->bin)
  349. ->condition('expire', CACHE_PERMANENT, '<>')
  350. ->condition('expire', $cache_flush, '<=')
  351. ->execute();
  352. }
  353. }
  354. /**
  355. * Prepare a cached item.
  356. *
  357. * Checks that items are either permanent or did not expire, and unserializes
  358. * data as appropriate.
  359. *
  360. * @param $cache
  361. * An item loaded from cache_get() or cache_get_multiple().
  362. * @return
  363. * The item with data unserialized as appropriate or FALSE if there is no
  364. * valid item to load.
  365. */
  366. protected function prepareItem($cache) {
  367. global $user;
  368. if (!isset($cache->data)) {
  369. return FALSE;
  370. }
  371. // If enforcing a minimum cache lifetime, validate that the data is
  372. // currently valid for this user before we return it by making sure the cache
  373. // entry was created before the timestamp in the current session's cache
  374. // timer. The cache variable is loaded into the $user object by _drupal_session_read()
  375. // in session.inc. If the data is permanent or we're not enforcing a minimum
  376. // cache lifetime always return the cached data.
  377. if ($cache->expire != CACHE_PERMANENT && variable_get('cache_lifetime', 0) && $user->cache > $cache->created) {
  378. // This cache data is too old and thus not valid for us, ignore it.
  379. return FALSE;
  380. }
  381. if ($cache->serialized) {
  382. $cache->data = unserialize($cache->data);
  383. }
  384. return $cache;
  385. }
  386. function set($cid, $data, $expire = CACHE_PERMANENT) {
  387. $fields = array(
  388. 'serialized' => 0,
  389. 'created' => REQUEST_TIME,
  390. 'expire' => $expire,
  391. );
  392. if (!is_string($data)) {
  393. $fields['data'] = serialize($data);
  394. $fields['serialized'] = 1;
  395. }
  396. else {
  397. $fields['data'] = $data;
  398. $fields['serialized'] = 0;
  399. }
  400. try {
  401. db_merge($this->bin)
  402. ->key(array('cid' => $cid))
  403. ->fields($fields)
  404. ->execute();
  405. }
  406. catch (Exception $e) {
  407. // The database may not be available, so we'll ignore cache_set requests.
  408. }
  409. }
  410. function clear($cid = NULL, $wildcard = FALSE) {
  411. global $user;
  412. if (empty($cid)) {
  413. if (variable_get('cache_lifetime', 0)) {
  414. // We store the time in the current user's $user->cache variable which
  415. // will be saved into the sessions bin by _drupal_session_write(). We then
  416. // simulate that the cache was flushed for this user by not returning
  417. // cached data that was cached before the timestamp.
  418. $user->cache = REQUEST_TIME;
  419. $cache_flush = variable_get('cache_flush_' . $this->bin, 0);
  420. if ($cache_flush == 0) {
  421. // This is the first request to clear the cache, start a timer.
  422. variable_set('cache_flush_' . $this->bin, REQUEST_TIME);
  423. }
  424. elseif (REQUEST_TIME > ($cache_flush + variable_get('cache_lifetime', 0))) {
  425. // Clear the cache for everyone, cache_lifetime seconds have
  426. // passed since the first request to clear the cache.
  427. db_delete($this->bin)
  428. ->condition('expire', CACHE_PERMANENT, '<>')
  429. ->condition('expire', REQUEST_TIME, '<')
  430. ->execute();
  431. variable_set('cache_flush_' . $this->bin, 0);
  432. }
  433. }
  434. else {
  435. // No minimum cache lifetime, flush all temporary cache entries now.
  436. db_delete($this->bin)
  437. ->condition('expire', CACHE_PERMANENT, '<>')
  438. ->condition('expire', REQUEST_TIME, '<')
  439. ->execute();
  440. }
  441. }
  442. else {
  443. if ($wildcard) {
  444. if ($cid == '*') {
  445. db_truncate($this->bin)->execute();
  446. }
  447. else {
  448. db_delete($this->bin)
  449. ->condition('cid', db_like($cid) . '%', 'LIKE')
  450. ->execute();
  451. }
  452. }
  453. elseif (is_array($cid)) {
  454. // Delete in chunks when a large array is passed.
  455. do {
  456. db_delete($this->bin)
  457. ->condition('cid', array_splice($cid, 0, 1000), 'IN')
  458. ->execute();
  459. }
  460. while (count($cid));
  461. }
  462. else {
  463. db_delete($this->bin)
  464. ->condition('cid', $cid)
  465. ->execute();
  466. }
  467. }
  468. }
  469. function isEmpty() {
  470. $this->garbageCollection();
  471. $query = db_select($this->bin);
  472. $query->addExpression('1');
  473. $result = $query->range(0, 1)
  474. ->execute()
  475. ->fetchField();
  476. return empty($result);
  477. }
  478. }