Set and Get Drupal cache data

Drupal has an inbuilt caching system, but it needs to be used effectively to get any benefit from it. For data accessed many times during the same request, data should be statically cached. If it's consistent over a longer period of time, it should also be added to the core cache.

The following is my template code that I used any time I need to pull something from the cache. I modify it based on what I expect to happen to the data.

function example_function($reset = FALSE) {
  $data = &drupal_static(__FUNCTION__);
 
  // Static cache for this call
  if (!$reset && $data) return $data;
 
  // Not in static cache, try the cache next
  $bin = 'cache';
  $cid = 'unique_cache_id';
  $expiry = CACHE_PERMANENT; // never expire this pls
  // or $expiry = REQUEST_TIME + 3600; // cache for one hour
 
  if (!$reset && $cid && ($cache = cache_get($cid, $bin))) {
    if (!empty($cache->data) && $cache->data != 'N;') {
      if ($cache->expire == CACHE_PERMANENT || REQUEST_TIME < $cache->expire) {
        // Stick in static cache
        $data = $cache->data;
        // Return data
        return $data;
      }
    }
  }
 
  // Data was not in static cache, or database/memcached cache
 
  // .. build data here
  // If data build has any kind of errors, return now rather than caching a bad value
  // unless that is your intention.
 
  if ($cid) {
    cache_set($cid, $data, $bin, $expiry);
  }
 
  return $data;
}

If the function is called many many times during a single page call, an additional step can be taken to store the reference to the static variable.

function example_function($reset = FALSE) {
  static $data = NULL;
  if (!isset($data)) {
    $data = &drupal_static(__FUNCTION__);
  }
 
  // .. etc.
}