3

I have a block, created with a custom block plugin (extending BlockBase), that shows on every page, and I want to cache its data, to speed up performance.

I have added cache tags to the build() function:

$build['#cache']['tags'] = $cache_tags;

But the build() function is still executing on each page load. I guess because the cache tags are for render cache, not data cache.

Is there a built in way to cache the data in the build() function for a block for logged in users?

Or do I have to add custom caching in the build function, like this:

if ($cache = \Drupal::cache()->get($cid)) {

https://api.drupal.org/api/drupal/core!core.api.php/group/cache/8.2.x

2 Answers 2

3

Blocks are cached by default. A block class with this build method:

public function build() {
    return [
      '#markup' => 'Block content',
    ];
  }

gets cached indefinitely or as long as you set in cache max-age.

If you add cache tags to the block that doesn't change whether the block is cached or not. The cache tags are used to invalidate cache items, not to store them. That is what cache keys are used for.

If the block gets cached, this is for logged in users, because the cache for anonymous users doesn't cache blocks, only pages.

1
  • Ah, yes. I tested with a simple block and that's true. I think what must be happening is that some part of the render array is causing the block to invalidate on each page load.
    – oknate
    Nov 9, 2016 at 18:58
2

One way to configure cache for a block is implement getCacheTags and getCacheContexts in your Block.

To cache per user, you can use this code:

PHP Code:

public function getCacheTags() {
  if ($user = \Drupal::currentUser()) {
    return Cache::mergeTags(parent::getCacheTags(), array('user:' . $user->id()));
  } else {
    return parent::getCacheTags();
  }
}

public function getCacheContexts() {
  return Cache::mergeContexts(parent::getCacheContexts(), array('user'));
}

Remember to import Drupal\Core\Cache\Cache in your Block class.

Copy this code to your Block and clear cache.

1
  • 1
    You don't need to do this. If you put the cache tags in the build array like the code example from the question they are merged the same way.
    – 4uk4
    Nov 9, 2016 at 18:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.