A Complete Guide to Custom Caching in Magento 2 (Updated 2019)

A Complete Guide to Custom Caching in Magento 2 (Updated 2019)
COMMENTS ()
Tweet

In this blog, I will explain how to create your own cache in Magento 2, and how to read and write data from that custom cache. I hope after reading this article you will find many ways to optimize your site’s performance.

What is Caching?

Caching is a high-speed layer of temporary data storage. In this process, relevant pieces of data are stored so that requests in the future for similar data can be served faster.

Caching helps applications work dramatically faster. By using Caching, you can efficiently reuse old retrieved and computed information. Retrieving data from cache is much faster than retrieving data directly from Databases

How does it work?

Initially, data is fetched from its primary source (e.g. Database) and stored in Cache. That piece of data can be retrieved and served from Cache rather than being fetched directly from the original source of data i.e. Database. Once the cache is flushed or cleaned, fresh or new data will be updated in the Cache.

Declare new cache

  • Create a file cache.xml inside following directory app/code/[Namespace]/[module]/etc/
  • Add the following content
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Cache/etc/cache.xsd">
    <type name=”folio3_customcache" instance="[namespace]\[module]\Model\Cache\Type">
        <label>Folio3 Custom Cache</label>
        <description>Custom Cache Storage by Folio3</description>
    </type>
</config>

Create Cache Model

  • Create file Type.php inside following directory app/code/[Namespace]/[module]/Model/Cache/
  • Add the following content:
<?php
namespace [namespace]\[module]\Model\Cache;

/**
 * System / Cache Management / Cache type "Custom Cache Tag"
 */
class Type extends \Magento\Framework\Cache\Frontend\Decorator\TagScope
{
    /**
     * Cache type code unique among all cache types
     */
    const TYPE_IDENTIFIER = 'folio3_customcache';

    /**
     * Cache tag used to distinguish the cache type from all other cache
     */
    const CACHE_TAG = 'FOLIO3_CUSTOMCACHE';
    
    const FOLIO3_CACHE_KEY = 'folio3_customcache';

    /**
     * @param \Magento\Framework\App\Cache\Type\FrontendPool $cacheFrontendPool
     */
    public function __construct(\Magento\Framework\App\Cache\Type\FrontendPool $cacheFrontendPool)
    {
        parent::__construct($cacheFrontendPool->get(self::TYPE_IDENTIFIER), self::CACHE_TAG);
    }
}
  • After that, go to System -> Cache Management
  • You will be able to see your Folio3 Custom Cache
  • Your cache is now successfully created!

How to store data into custom cache?

You can store data in a serialized form into your custom cache in the following way

1. Pass this argument to constructor \Magento\Framework\App\CacheInterface $cache

 2. Inside constructor, add $this->_cache = $cache;

3. Then use the following snippet to store data

//Cache Identifier
$cacheKey  = \[namespace]\[module]\Model\Cache\Type::FOLIO3_CACHE_KEY;

//Store Data in Cache
          	$storeData = $this->_cache->save(
serialize($cacheData), $cacheKey, array(\[namespace]\[module]\Model\Cache\Type::CACHE_TAG), 
86400);

How to retrieve data from custom cache in Magento 2?

You can easily retrieve data from your custom cache using below snippet

//Cache Identifier
$cacheKey  = \[namespace]\[module]\Model\Cache\Type::FOLIO3_CACHE_KEY;

//Get unserialized data from Cache
$data = unserialize($this->_cache->load($cacheKey));

How to invalidate custom cache?

    • You would definitely want to invalidate your custom cache after making any changes to the data stored in your custom cache
    • You can invalidate your custom cache in the following way
      1. Pass this argument to constructor \Magento\Framework\App\Cache\TypeListInterface $typeList
      2. Inside the constructor, add $this->_typeList = $typeList;
      3. Then use the following snippet to store data
$this->_typeList->invalidate(

\[namespace]\[module]\Model\Cache\Type::FOLIO3_CACHE_KEY);

How to flush custom cache ?

    • You can flush cache in the following ways
      1. Go to System -> Cache Management and flush Folio3 Custom Cache
      2. Programatically, you can flush in a following way
        • Pass this argument to constructor \Magento\Framework\App\Cache\TypeListInterface $cacheTypeList,
        • Inside the constructor, add $this->cacheTypeList = $cacheTypeList;
        • Then use the following snippet to flush your custom cache
$this->cacheTypeList->cleanType(
\[namespace]\[module]\Model\Cache\Type::FOLIO3_CACHE_KEY);

Conclusion

Using caching mechanism in your application can drastically boost your site’s performance. This will help return much faster responses to users who are requesting data from the store. Instead of fetching from the databases, the requested data will be returned from the cache.

The concept is similar to Full Page Cache. FPC caches data like Product Detail Pages, Category Listing Pages. You can similarly use custom caching to store commonly requested data as well.

For example list of cities that are displayed at checkout’s shipping/billing address form can be cached. So that every time a user goes to the checkout page, a list of cities will be returned from the cache instead of the database directly. In this way, you can reduce a large number of requests from database

Don’t forget to share your feedback in the comments section. Thank you 🙂

 

CALL

USA408 365 4638

VISIT

1301 Shoreway Road, Suite 160,

Belmont, CA 94002

Contact us

Whether you are a large enterprise looking to augment your teams with experts resources or an SME looking to scale your business or a startup looking to build something.
We are your digital growth partner.

Tel: +1 408 365 4638
Support: +1 (408) 512 1812