Drupal caching with cache_get , cache_set , and cache_clear_all

Drupal caching with cache_get , cache_set , and cache_clear_all

We all know Drupal is a little ‘heavy’ when it comes to database queries. Using caching for some of your data can greatly improve load times and reduce server loads. Custom caching can be used for a variety of reasons. I like to use it for user-specific sections that Drupal doesn’t like to cache (if I can’t use the built-in caching like block caching).

In the following example, I want to save some user-specific data:

global $user;

// save data - uses the default CACHE_PERMANENT
cache_set('mymodule_userdata_' . $user->uid, $user_data);

// or save data with an expiration date - 24 hours in this case
$expire = strtotime("+24 hours", time());
cache_set('mymodule_userdata_' . $user->uid, $user_data, 'cache', $expire);

// get the data back
$cache = cache_get('mymodule_userdata_' . $user->uid);
if (isset($cache->data)) {
  $user_data = $cache->data;

// reset cache for some reason - maybe user updated record and need to get new data
cache_clear_all('mymodule_userdata_' . $user->uid, 'cache');

These few functions could save you tons of time on page load and resources.

Comments are closed.