Site icon MageComp Blog

How to clean and flush cache programmatically in magento2

programmatically Caching M2

programmatically Caching M2

Magento Store Performance & speed of your store plays a vital role to serve a great shopping experience to your shoppers. Also, its important ranking factor that keeps you stand out from the competition. Adding more products & data to your store simultaneously increases the possibility of making your store slower to load. Magento cache management is a handy tool to flush the cache and release storage by removing unnecessary catalog image cache and the JavaScript as well as CSS cache.

Magento offers several types of caching as per need. But after a modifying code or making changes that might affect HTML output on the store frontend, it’s highly recommended to keep Magento cache enabled. Working with Magento extension development, many times you need to flush cache programmatically to apply drastic changes on the store frontend. Recently, while developing an extension, we have implemented programmatically cache to get quick effects on store data. Today I would likely to share that code with you guys.

All you need to do is simply need to add the following code to your extension file.

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

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

public function cachePrograme()
{

	$_cacheTypeList = $this->typeListInterface;

	$_cacheFrontendPool = $this->pool;

	$types = array('full_page');

	foreach ($types as $type) 
	{
		$_cacheTypeList->cleanType($type);
	}
	foreach ($_cacheFrontendPool as $cacheFrontend) 
	{
	$cacheFrontend->getBackend()->clean();
	}
}

Voila, now you successfully implemented programmatically cache. You can manipulate this code according to your requirements of caching.

Do comment if you are facing any issue while using this code.

Happy Caching!

Exit mobile version