How to clean and flush cache programmatically in magento2

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!

Quick Cache and Reindex

Previous Article

EGG-xtra Special Savings on Easter! Up to 30% Off on Magento Extensions

Next Article

How to display “Free” for product with $0.00 price in Magento 2

Write a Comment
  1. I’ve tried this code and also using Magento\Framework\App\Cache\Manager method, but cache is not cleared, I’ve written code in Block file. What could be the issue?
    Manually flushing the cache works fine.

Leave a Comment

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

Get Connect With Us

Subscribe to our email newsletter to get the latest posts delivered right to your email.
Pure inspiration, zero spam ✨