Get Free Audit

How to Use a Default Cache in Magento 2.0

Feb 4, 2016

1727 Andrei Danilchyk

How to Use a Default Cache in Magento 2.0

Very often when developing extensions or custom solutions it is necessary to cache certain information. In this case the best solution is to use the default Magento cache. It’s relatively easy to use and has only a few distinctions from how it’s made in the default Magento 1.x.

First of all, you need to register a new cache type. This is necessary to make it work as with any other default Magento cache so you could  clear / enable / disable it from the admin panel:

Then we create instance for the new custom cache:

Notice that the class \Magento\Framework\Cache\FrontendInterface is the interface for the cache model. But we use the class \Magento\Framework\Cache\Frontend\Decorator\TagScope because this class contains a very important functionality for clearing cache by tags.

Vlad Yunusov
Partner With Us Let's discuss how to grow your business. Get a Free Quote.
Talk to Vlad

The method $this->getTag() in this case will return the value \BelVG\Infscroll\Model\Cache\Type::CACHE_TAG transmitted via  __constract when creating a class object. Now we can:

  • add (method save)
  • upload (method load)
  • remove a separate inscription by identificator (method remove)
  • cleaning all cache or some particular types only (method clean)

At this point, everything is ready. New cache type is displayed in the ‘Cache Management’  in the admin panel and this cache type can be used as a default Magento cache:


Now you can work with this cache type directly via class object BelVG\Infscroll\Model\Cache\Type (for example, by extending its functionality) or create a separate helper, for example:

In this helper we added a check on current cache status:

and a function that generates the identificator for cache inscriptions:

This is a very important moment, because the identificator should be unique for each data sequence. For example, if we have a function that sends requests to a 3rd-party service by transferring certain parameters, then the identificator is generated based on

  • the name of the method in 3rd-party service ($method);
  • the values of the transferred parameter ($vars).

In this case, each unique data sequence from the 3rd-party service will be cached as a separate inscription.

Vlad Yunusov
Partner With Us Looking for a partner that will help you to grow your business? We are the right company to develop your webstore. Feel free to get in touch with us. We will be happy to discuss your business opportunities and provide you with a Free Quote. Talk to Vlad

Post a new comment

BelVG Newsletter
Subscribe to our mailing list and get interesting stuff and updates to your email inbox.
Email *