Magento 2 Clear Cache Programmatically

Sometimes we have the requirement to clear cache programmatically. We have the below lines of code to explain how we can do this with a class method which is created as Helper class.

Create the following helper class:

<?php

namespace Magemeta\Cache\Helper;

use Magento\Framework\App\Cache\TypeListInterface;
use Magento\Framework\App\PageCache\Version;
use Magento\Framework\App\Cache\Frontend\Pool;

class Data {
    protected $cacheTypeList;
    protected $cacheFrontendPool;

    public function __construct(
        TypeListInterface $cacheTypeList, 
        Pool $cacheFrontendPool
    ){
        $this->cacheTypeList = $cacheTypeList;
        $this->cacheFrontendPool = $cacheFrontendPool;
    }

    public function cleanCache(Version $subject)
    {
        $types = [
        'config',
        'layout',
        'block_html',
        'collections',
        'reflection',
        'db_ddl',
        'eav',
        'config_integration',
        'config_integration_api',
        'full_page',
        'translate',
        'config_webservice'
        ];

        foreach ($types as $type) {
            $this->cacheTypeList->cleanType($type);
        }

        foreach ($this->cacheFrontendPool as $cacheFrontend) {
            $cacheFrontend->getBackend()->clean();
        }
    }
}

Now you can call cleanCache() method anywhere you want like in a controller or model.

Leave a Reply