Programatically clearing Magento 2 block and page caches

13 JanuaryJan, 2017
Robert Egginton

magento 2 cache

Well, that title is a mouthful, but incrementally clearing caches is a really important issue. Magento 2 makes extensive use of both block and full-page caching, so making sure that it’s cleared fully when required, but no more than required, means that you can trust the data shown and the site will be fast.

Much of the time this is taken care of for you – the afterSave() method of the abstract model class clears both the block and full-page caches for that model. This means that all pages tagged with that model’s tags will get cleared.

Let’s take the product class as an example. After save, product view and category page containing that product will get cleared.

Q. What if you make changes to products without a full save?

A common task is to make a small changes to a product using save Attribute e.g.

$product->getResource()->saveAttribute($product, 'price');

This makes a direct change and bypasses the afterSave() method. So we need to clear the block and full-page caches ourselves. Luckily, we can just use the code from the abstract model:

$product->cleanCache();
$this->_eventManager->dispatch('clean_cache_by_tags', ['object' => $product]);

The first gets the cache_tags from the model and passes them to the cacheManager for selective clearing. The latter fires an event so that either the built-in full-page cache or the varnish cache manager can handle clearing by identities taken from the object.

Q: What about other models?

The cleanCache() method is also implemented on the abstract model, so this should work for any model that has this as an ancestor (i.e. all created in a sensible way). And the clean_cache_by_tags will work with any object that implements IdentityInterface (which will be most models).

Q: What about my own models.

What indeed! It’s important to set cache tags and implement the identity interface; and include these tags on relevant blocks. Then the above code will work for these models as well.

That’s rather short on detail, but we’ll be releasing a more detailed blog post about implementing caching for your own Magento 2 modules shortly 🙂

ABOUT THE AUTHOR

Robert Egginton

As our chief problem-solver and systems architect, Rob is involved in every aspect of our development processes. Rob is partial to a bit of improvisational theatre, and setting up a smart home on a budget.