Magento 2 : How to create your own cache type ?

Create your own cache type is common business requirement. Today we gonna learn how to create custom cache type which not only cache the data object but you can also delete cached data from the Magento backend Cache Management.

Bajaj/CustomCache/etc/cache.xml

<?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="bajaj_custom_cache" translate="label,description" instance="Bajaj\CustomCache\Model\Cache\Type">
        <label>Bajaj Custom Cache</label>
        <description>Bajaj Custom cache for storing the objects</description>
    </type>
</config>

Bajaj/CustomCache/Model/Cache/Type.php

<?php

namespace Bajaj\CustomCache\Model\Cache;

/**
 * Class Type
 * @package Bajaj\CustomCache\Model\Cache
 */
class Type extends \Magento\Framework\Cache\Frontend\Decorator\TagScope
{
    /**
     * Cache type code unique among all cache types
     */
    const TYPE_IDENTIFIER = 'bajaj_custom_cache';

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

    /**
     * Type constructor.
     * @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);
    }
}
Bajaj Custom Cache Type

To enable the custom cache type run the following command:

bin/magento cache:enable bajaj_custom_cache

➜  magento2 $ bin/magento cache:enable bajaj_custom_cache
Changed cache status:
            bajaj_custom_cache: 0 -> 1
Cleaned cache types:
bajaj_custom_cache

So when you run bin/magento cache:clean bajaj_custom_cache for example, all cached data with the BAJAJ_CUSTOM_CACHE tag are deleted.

➜  magento2 $ bin/magento c:f                            
Flushed cache types:
config
layout
block_html
collections
reflection
db_ddl
eav
bajaj_custom_cache
customer_notification
config_integration
config_integration_api
full_page
config_webservice
translate
vertex

Leave a Reply

Your email address will not be published. Required fields are marked *