cache clear and cache flush in adobe commerce

Clearing or Flushing Cache Programmatically in Magento 2

Posted by

Cache management is crucial for ensuring a smooth and high-performance Magento 2 store. Clearing or flushing the cache is a common task, and while it can be done manually through the admin panel, there are scenarios where doing it programmatically becomes necessary. In this article, we will explore the process of clearing or flushing cache programmatically in Magento 2 and understand when and why this approach is beneficial.

Clearing Cache Programmatically in Magento 2

<?php
namespace Vendor\Model\Helper;

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

class CacheClearer
{
    protected $cacheTypeList;
    protected $cachePool;

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

    public function clearCache()
    {
        $cacheTypes = array_keys($this->cacheTypeList->getTypes());
   
        foreach ($cacheTypes as $type) {
            $this->cacheTypeList->cleanType($type);
        }
    }

    public function flushCache() 
    {
         foreach ($this->cachePool as $cacheFrontend) {
            $cacheFrontend->getBackend()->clean();
        }
    }
}

Clear cache in Magento 2 and Adobe commerce

Now you have the freedom to integrate the above class into any of your class constructors. To initiate the cache clearing process for Magento 2 | Adobe Commerce, simply employ the clearCache() method.

The getTypes() method within $this->cacheTypeList offers an array containing all cache types. Store their keys in a variable named $cacheType, and then efficiently loop through them utilizing a for loop. Employ the cleanType() method from TypeListInterface to effectively clean each specific cache

Flush cache in Adobe commerce and Magento 2

To initiate a cache flush, you can seamlessly utilize the following method within the CacheClearer class – aptly named flushCache(). This method orchestrates a loop mechanism that systematically flushes the entire cache storage, ensuring a comprehensive cleaning process across the system.

Leave a Reply

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