Skip to content

Instantly share code, notes, and snippets.

@crittermike
Last active August 25, 2018 16:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save crittermike/9768a628537a8870ea8f2a90856bffc6 to your computer and use it in GitHub Desktop.
Save crittermike/9768a628537a8870ea8f2a90856bffc6 to your computer and use it in GitHub Desktop.
Cache get/set examples for Drupal 7 and Drupal 8

Drupal 7

Setting the cache

cache_set('cache_key_goes_here', 'cache_data_goes_here', 'cache', time() + 60);

Fetching the cache

$cache = cache_get('cache_key_goes_here');
if (!empty($cache->data) && time() < $cache->expire) {
  // Do something with $cache->data here.
}

Drupal 8

Setting the cache

\Drupal::cache()->set('cache_key_goes_here', 'cache_data_goes_here', time() + 60);

Fetching the cache

$cache = \Drupal::cache()->get('cache_key_goes_here');
if (!empty($cache->data) {
  // Do something with $cache->data here.
}

Note that in Drupal 8 you don't have to manually check to make sure the cache isn't expired, thanks to this issue.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment