Magento uses many cache types out of the box; being very convenient for both administrators and developers, due to its decentralized design that provides specialized caching for different purposes.

When using Magento, its architecture will manage and determine the best cache type and policy to use for every particular situation; providing a more powerful solution compared with other frameworks that only provide single cache storage.

Magento is also flexible enough to allow you as a developer to implement and utilize a custom cache for any specific purpose. The process is very simple for any developer; in the following examples let’s suppose that we are working with an existent module called Astralweb_Cache. The basic procedure for using Magento cache would include the following procedures:

  1. Create a cache XML file

Create a new file in AstralWeb/Cache/etc/cache.xml with 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=”astralweb_cache” translate=”label,description” instance=”AstralWeb\Cache\Model\Cache\AstralWebCache”>

        <label>AstralWeb Cache</label>

        <description>AstralWeb Custom Cache</description>

    </type>

</config>

In which:

name: This is the unique and internal cache code to be used for identifying the cache. 

instance: The PHP class will be responsible for constructing the custom cache type.

  1. Create the class AstralWen\Cache\Model\Cache\AstralWebCache

<?php

namespace AstralWeb\Cache\Model\Cache;

use Magento\Framework\App\Cache\Type\FrontendPool;

use Magento\Framework\Cache\Frontend\Decorator\TagScope;

/**

 * System / Cache Management / Cache “Label”

 */

class AstralWebCache extends TagScope

{

    /**

     * The unique and internal code to be used for identifying the cache.

     */

    const TYPE_IDENTIFIER = ‘astralweb_cache’;

    /**

     * The tag name used for identifying the cache scope

     */

    const CACHE_TAG = ‘ASTRALWEB_CACHE_TAG’;

    /**

     * @param FrontendPool $cacheFrontendPool

     */

    public function __construct(FrontendPool $cacheFrontendPool)

    {

        parent::__construct(

            $cacheFrontendPool->get(self::TYPE_IDENTIFIER),

            self::CACHE_TAG

        );

    }

}

After that you will be able to see AstralWeb Cache in System → Cache Management, meaning that the cache has been successfully created.

  1. Using the custom cache

After creating the custom cache the most common way to insert data into it is by injection into almost any class that requires inserting data.

use Magento\Framework\App\CacheInterface;

use Magento\Framework\Serialize\SerializerInterface;

use Magento\Framework\App\Cache\TypeListInterface 

use AstralWeb\Cache\Model\Cache\AstralWebCache;

….

….

….

protected $_cache;

protected $_serializer;

protected $_cacheTypeList;

/**

 * @param CacheInterface $_cache

 * @param SerializerInterface $_serializer

 */

public function __construct(

CacheInterface $cache, 

SerializerInterface $serializer,

CacheTypeList $cacheTypeList

)

{

    $this->_cache = $cache;

    $this->_serializer = $serializer;

    $this->_cacheTypeList = $cacheTypeList;

}

….

….

….

  1. Saving data into the custom cache

The following example illustrates how to insert custom data into the cache. You should notice that the data, or object, to be saved is serialized into a string.

public function saveToCache($dataToSave)

{

    $cacheKey  = AstralWebCache::TYPE_IDENTIFIER;

    $cacheTag  = AstralWebCache::CACHE_TAG;

    $storeData = $this->_cache->save(

        $this->_serializer->serialize($dataToSave), // Serialization

        $cacheKey,

        [$cacheTag],

        86400 // lifetime of the cached data (seconds)

    );

}

  1. Reading data from the custom cache

Reading data from custom cache is exactly the opposite process. You should note that the data or object will be unserialized.

public function readFromCache()

{

    $cacheKey  = AstralWebCache::TYPE_IDENTIFIER;

    $data = $this->_serializer->unserialize($this->_cache->load($cacheKey));

}

Please note that the data from the custom cache will be accessible until it reaches lifetime and before the Administrator flushes the cache. Also, if the saved data has been re-saved with different data, it will not be retrieved correctly until the cache is flushed.

  1. Invalidating the custom cache

If after re-saving the cache with different data you would like to display the cache as “invalid” to the Administrator you need to execute the following code.

public function invalidateCache()

{

    $this->_cacheTypeList->invalidate(AstralWebCache::TYPE_IDENTIFIER);

}

  1. Flushing the custom cache type

You can flush the cache manually on System → Cache Management, but you can also flush the cache programmatically as this:

public function flushCache()

{

    $this->_cacheTypeList->cleanType(AstralWebCache::TYPE_IDENTIFIER);

}

The only disadvantage of using Magento cache for your own cache is that you will not be able to configure it according to your needs, or you might not be able to reduce the abstraction layers you would like for simplifying the process even more.

However, the above approach will allow you to provide a faster response by using Magento internal cache mechanism. Instead of fetching from the databases, the requested data will be returned from the cache.