Magento 2: How to Invalidate and Flush Custom Cache Type?

Invalidate and Flush Custom Cache in Magetno 2

Let’s see how we can Invalidate and Flush Custom Cache? We have created a custom cache type https://sbdevblog.com/magento-2-how-to-create-custom-cache/ as well as we have saved and retrieved data from the cache https://sbdevblog.com/magento-2-store-retrieve-from-the-custom-cache/

Invalidate and Flush Custom Cache?

Sometimes we require to invalidate the cache on a certain event like blog creation. Let’s see how can we invalidate that cache using code.

We require to use Magento\Framework\App\Cache\TypeListInterface in order to Invalidate or Flush the cache type.

<?php
/**
 * @copyright Copyright (c) sbdevblog (https://www.sbdevblog.com)
 */

namespace SbDevBlog\Cache\Services;

use Magento\Framework\App\Cache\TypeListInterface;

class InvalidateAndFlushCustomCache
{
    /**
     * @var TypeListInterface
     */
    private TypeListInterface $typeList;

    public function __construct(
        TypeListInterface $typeList
    ){
        $this->typeList = $typeList;
    }

    /**
     * Invalidate cache
     *
     * @param array $type
     * @return void
     */
    public function invalidateCache(array $type):void
    {
        $this->typeList->invalidate($type);
    }
}
Let’s flush the custom cache type
<?php
/**
 * @copyright Copyright (c) sbdevblog (https://www.sbdevblog.com)
 */

namespace SbDevBlog\Cache\Services;

use Magento\Framework\App\Cache\TypeListInterface;

class InvalidateAndFlushCustomCache
{
    /**
     * @var TypeListInterface
     */
    private TypeListInterface $typeList;

    public function __construct(
        TypeListInterface $typeList
    ){
        $this->typeList = $typeList;
    }

    /**
     * Flush cache by Type
     *
     * @param string $type
     * @return void
     */
    public function flushCache(string $type):void
    {
        $this->typeList->cleanType($type);
    }
}

That’s the simple way to invalidate as well as flush any type of cache. Thanks for reading SbDevBlog. Please use the comment box for your feedback.

Download Source Code

Note: Please verify the code of this blog and the relevant git repository before using it in production.
sb dev blog adobe commece Magento 2

🙂 HAPPY CODING 🙂

2 thoughts on “Magento 2: How to Invalidate and Flush Custom Cache Type?

Leave a Reply

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