How to use Cache API in Drupal

Learn the Cache API in Drupal 7 and 8This is a very simple tutorial that could help you with the performance of your custom modules. I will show you how to use Cache API in Drupal 8 and Drupal 7.

You don't have to perform heavy calculations every time you need to pull data either from third-party API or from database. Instead run it once and cache it. I personally use caching when I need to run complex SQL queries and third-party integrations (Example: get a list of available forms from Hubspot, or available campaign lists from Mailchimp etc).

In Drupal 8 use the following code structure:

public function mymodule_example_cache() {
  $data = &drupal_static(__FUNCTION__); // Can be replaced with the `__METHOD__`
  $cid = 'mymodule_example:' . \Drupal::languageManager()->getCurrentLanguage()->getId();

  if ($cache = \Drupal::cache()->get($cid)) {
    $data = $cache->data;
  }
  else {
    // This is where you would add your code that will run only
    // when generating a new cache.
    $data = my_module_complicated_calculation();
    \Drupal::cache()->set($cid, $data);
  }
  return $data;
}

In Drupal 7 the following:

function mymodule_example_cache() {
  $data = &drupal_static(__FUNCTION__);
  if (empty($data)) {
    if ($cache = cache_get('mymodule_example')) {
      $data = $cache->data;
    }
    else {
      // This is where you would add your code that will run only
      // when generating a new cache.
      $data = my_module_complicated_calculation();
      cache_set('mymodule_example', $data, 'cache');
    }
  }
  return $data;
}

 

Useful links

  1. Drupal 8 API: Cache API
  2. Drupal 8 API: function drupal_static
  3. Drupal 7 API: function cache_set
  4. Drupal 7 API: function cache_get
  5. Drupal 7 API: function drupal_static