How to flush and clean cache programmatically in Magento 2

Here, we will learn how to flush and clean cache programmatically.

Magento provide several types of caching as per demand. As you know, we have enabled Magento cacha for better performance of our store/website. In some custom module development (example: to import/update entity) we must need to flush and clean Magento cache so it’s affect on the front-end.

we suggest you to run flush cache programmatically after your custom module process executed so that admin user no need to perform flush cache manually and your entity changes directly affected at the store frontend.

Flush and clean cache programmatically

protected $_cacheTypeList;
protected $_cacheFrontendPool;


public function __construct(
    Context $context,
    \Magento\Framework\App\Cache\TypeListInterface $cacheTypeList,
    \Magento\Framework\App\Cache\Frontend\Pool $cacheFrontendPool
) {
    parent::__construct($context);
    $this->_cacheTypeList = $cacheTypeList;
    $this->_cacheFrontendPool = $cacheFrontendPool;
}

public function flushCacheRun()
{
	$cacheTypes = array('config','layout','block_html','collections','reflection','db_ddl','eav','config_integration','config_integration_api','full_page','translate','config_webservice');
	foreach ($cacheTypes as $type) {
		$this->_cacheTypeList->cleanType($type);
	}

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

That’s all about flush and clean Magento 2 Cache! we hope this technical blog is useful for you. please leave comment if you have any queries.

How to Run Reindexing Programmatically

Thank You):

Related Posts

Leave a Reply

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