$result = &drupal_static(__FUNCTION__); if (!isset($result)) { if ($cache = cache_get('my_query_result')) { $result = $cache->data; } else { $result = db_query('SELECT * FROM my_table')->fetchAll(); cache_set('my_query_result', $result, 'cache', strtotime('+1 week')); } }
$block = module_invoke('my_module', 'block_view', 'my_block'); $output = &drupal_static('my_block_output'); if (!isset($output)) { if ($cache = cache_get('my_block_output')) { $output = $cache->data; } else { $output = render($block); cache_set('my_block_output', $output, 'cache_block', strtotime('+1 hour')); } } print $output;
function my_module_get_data($arg1, $arg2) { $cache_key = 'my_module_get_data:' . $arg1 . ':' . $arg2; $cache_tags = array('my_tag1', 'my_tag2'); $data = &drupal_static(__FUNCTION__); if (!isset($data)) { if ($cache = cache_get($cache_key)) { $data = $cache->data; } else { // Expensive function call to retrieve data $data = my_expensive_function($arg1, $arg2); cache_set($cache_key, $data, 'cache', strtotime('+1 hour'), $cache_tags); } } return $data; }This example caches the result of a custom function using a cache key and cache tags. The `drupal_static` function is used to store the result in a static variable for faster access on subsequent calls. Package library: Drupal Core or Drupal Cache API module.