function cache_set

You are here

7 cache.inc cache_set($cid, $data, $bin = 'cache', $expire = CACHE_PERMANENT)
4.6 bootstrap.inc cache_set($cid, $data, $expire = CACHE_PERMANENT, $headers = NULL)
4.7 bootstrap.inc cache_set($cid, $data, $expire = CACHE_PERMANENT, $headers = NULL)
5 cache.inc cache_set($cid, $table = 'cache', $data, $expire = CACHE_PERMANENT, $headers = NULL)
6 cache.inc cache_set($cid, $data, $table = 'cache', $expire = CACHE_PERMANENT, $headers = NULL)
6 cache-install.inc cache_set($cid, $data, $table = 'cache', $expire = CACHE_PERMANENT, $headers = NULL)

Stores data in the persistent cache.

The persistent cache is split up into several cache bins. In the default cache implementation, each cache bin corresponds to a database table by the same name. Other implementations might want to store several bins in data structures that get flushed together. While it is not a problem for most cache bins if the entries in them are flushed before their expire time, some might break functionality or are extremely expensive to recalculate. The other bins are expired automatically by core. Contributed modules can add additional bins and get them expired automatically by implementing hook_flush_caches().

The reasons for having several bins are as follows:

  • Smaller bins mean smaller database tables and allow for faster selects and inserts.
  • We try to put fast changing cache items and rather static ones into different bins. The effect is that only the fast changing bins will need a lot of writes to disk. The more static bins will also be better cacheable with MySQL's query cache.

Parameters

$cid: The cache ID of the data to store.

$data: The data to store in the cache. Complex data types will be automatically serialized before insertion. Strings will be stored as plain text and are not serialized.

$bin: The cache bin to store the data in. Valid core values are:

  • cache: (default) Generic cache storage bin (used for theme registry, locale date, list of simpletest tests, etc.).
  • cache_block: Stores the content of various blocks.
  • cache_bootstrap: Stores the class registry, the system list of modules, the list of which modules implement which hooks, and the Drupal variable list.
  • cache_field: Stores the field data belonging to a given object.
  • cache_filter: Stores filtered pieces of content.
  • cache_form: Stores multistep forms. Flushing this bin means that some forms displayed to users lose their state and the data already submitted to them. This bin should not be flushed before its expired time.
  • cache_menu: Stores the structure of visible navigation menus per page.
  • cache_page: Stores generated pages for anonymous users. It is flushed very often, whenever a page changes, at least for every node and comment submission. This is the only bin affected by the page cache setting on the administrator panel.
  • cache_path: Stores the system paths that have an alias.

$expire: One of the following values:

  • CACHE_PERMANENT: Indicates that the item should never be removed unless explicitly told to using cache_clear_all() with a cache ID.
  • CACHE_TEMPORARY: Indicates that the item should be removed at the next general cache wipe.
  • A Unix timestamp: Indicates that the item should be kept at least until the given time, after which it behaves like CACHE_TEMPORARY.

See also

_update_cache_set()

cache_get()

49 calls to cache_set()
archiver_get_info in includes/common.inc
Retrieves a list of all available archivers.
book_menu_subtree_data in modules/book/book.module
Gets the data representing a subtree of the book hierarchy.
CacheClearCase::testClearArray in modules/simpletest/tests/cache.test
Test clearing using an array.
CacheClearCase::testClearCid in modules/simpletest/tests/cache.test
Test clearing using a cid.
CacheClearCase::testClearWildcard in modules/simpletest/tests/cache.test
Test clearing using wildcard.

... See full list

File

includes/cache.inc, line 133
Functions and interfaces for cache handling.

Code

function cache_set($cid, $data, $bin = 'cache', $expire = CACHE_PERMANENT) {
  return _cache_get_object($bin)->set($cid, $data, $expire);
}

Comments

...pass $cid and $bin to the misleadingly named cache_clear_all()

Simple example of using cache in your functions

<?php
function steam_get_username2($steam64)  {
  if(
$cached = cache_get('steam'.$steam64, 'cache'))  {
   
$username = $cached->data;
  }
  if(empty(
$username)) {
   
$username = 'blank'; // Expensive code here
 
}
 
cache_set('steam'.$steam64, $username, 'cache', 60*60); //1 hour
 
return $username;
}
?>

Shouldn't the expire time be added to the current time?

Like this:

cache_set('steam'.$steam64, $username, 'cache', time() + 60*60);

cache_set() is being called on every invokation. It should only be called when the data is rebuilt.

<?php
function steam_get_username2($steam64)  {
  if(
$cached = cache_get('steam'.$steam64, 'cache'))  {
   
$username = $cached->data;
  }
  if(empty(
$username)) {
   
$username = 'blank'; // Expensive code here
   
cache_set('steam'.$steam64, $username, 'cache', time() + 60*60); //1 hour
 
}
  return
$username;
}
?>

Use REQUEST_TIME rather than time().... but yeah you'd need to treat it as a timestamp so 360 would be some time in 1970.

Edit: this was supposed to be a reply to chrisroane's comment but I guess I clicked the wrong reply link.

Good catch!

The only way I could get the caching to work as expected in a custom function was to also use &drupal_static(__FUNCTION__) ....Below is a simplified version of what I got working:

function _tbf_cart_get() {
  // This makes sure we only do the heavy lifting from this module one time
  // per page load.
  $cart = &drupal_static(__FUNCTION__);
 
  if (!$cart) {
    $cache_id = 'tbf_cart:cart:' . $_SESSION['cart']['orderid'];
     
    // Grab the data from the cache.
    $cache = cache_get($cache_id, 'cache');
    if ($cache && !empty($cache->data)) {
      $cart = $cache->data;
      return $cart;
    }
   
    // Add the data to $cart...
   
    // Add the data to the cache.
    cache_set($cache_id, $cart);
  }
 
  return $cart;
}

The $expire option CACHE_TEMPORARY says

Indicates that the item should be removed at the next general cache wipe.

How is the next general cache wipe triggered? Is it triggered by cron jobs? Is it triggered every hour or every day?

@technicalknockout Yes, it happens on cron run by default, so how often depends on what you have cron set to.

Is there any way that i can wipe cache after some minutes?

Try the Elysia cron module for more fine grained control of the cron service. If that is not enough, implement cache_clear_all() or take a look at the code of drupal_flush_all_caches() for more ideas.

Not 100% sure but i think Rules could also do this.

Example with strtotime(), maybe for a more clean and easy way for getting a cache to expire in 6 hours:

<?php
$cache_time
= '+6 hour';
$expire = strtotime($cache_time, time());
cache_set('resource:' . $name, $result, 'cache_clients', $expire);
?>

This way I can have a select form element with values like '+1 hour', '+6 hour', '+1 day', etc...

Cheers!