Upgrade Your Drupal Skills

We trained 1,000+ Drupal Developers over the last decade.

See Advanced Courses NAH, I know Enough

Drupal 8 Cache API examples cheat sheet

Parent Feed: 

Here are some random useful snippets for dealing with caches in Drupal 8, just because I keep having to dig them up from the API.

I’ll try to add more here as I go.

set('cache_key', 'cache_data', $expiration_timestamp);

// Set a permanent cache item
\Drupal::cache()->set('cache_key', 'cache_data', CacheBackendInterface::CACHE_PERMANENT);

// Set a permanent cache item with tags.
\Drupal::cache()->set('cache_key', 'cache_data', CacheBackendInterface::CACHE_PERMANENT, array('tag_one', 'second_tag'));

// Fetch an item from the cache
$cache = \Drupal::cache()->get('cache_key');
if (!empty($cache->data) {
  // Do something with $cache->data here.
}

// Invalidate a cache item
\Drupal::cache()->invalidate('cache_key');

// Invalidate multiple cache items
\Drupal::cache()->invalidateMultiple($array_of_cache_ids);

// Invalidate specific cache tags
use Drupal\Core\Cache\Cache;

Cache::invalidateTags(['config:block.block.YOURBLOCKID', 
  'config:YOURMODULE.YOURCONFIG', 'node:YOURNID']);

// Note that the invalidation functions also exist for deleting caches,
// by just replacing invalidate with delete.

// Flush the entire site cache.
drupal_flush_all_caches();

The end!

Original Post: 

About Drupal Sun

Drupal Sun is an Evolving Web project. It allows you to:

  • Do full-text search on all the articles in Drupal Planet (thanks to Apache Solr)
  • Facet based on tags, author, or feed
  • Flip through articles quickly (with j/k or arrow keys) to find what you're interested in
  • View the entire article text inline, or in the context of the site where it was created

See the blog post at Evolving Web

Evolving Web