Skip to content

Instantly share code, notes, and snippets.

@graceman9
Last active August 29, 2015 14:05
Show Gist options
  • Save graceman9/d692952204937db5125b to your computer and use it in GitHub Desktop.
Save graceman9/d692952204937db5125b to your computer and use it in GitHub Desktop.
Drupal 7: custom data caching - static variables, cache_set()/cache_get()
<?php
/**
* See:
* https://www.lullabot.com/blog/article/beginners-guide-caching-data-drupal-7
*/
// example 1
function my_module_function() {
$my_data = &drupal_static(__FUNCTION__);
if (!isset($my_data)) {
// Do your expensive calculations here, and populate $my_data
// with the correct stuff..
}
return $my_data;
}
// example 2
function my_module_function() {
$my_data = &drupal_static(__FUNCTION__);
if (!isset($my_data)) {
if ($cache = cache_get('my_module_data')) {
$my_data = $cache->data;
}
else {
// Do your expensive calculations here, and populate $my_data
// with the correct stuff..
cache_set('my_module_data', $my_data, 'cache');
}
}
return $my_data;
}
// example 3 - my example, rare case
function my_module_function() {
$my_data = &drupal_static(__FUNCTION__);
$my_data_helper = &drupal_static(__FUNCTION__ .'_helper');
if (!isset($my_data_1)) {
// $my_data_helper may take part in building of $my_data
}
return $my_data;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment