In this post, let’s find out how to clear/flush cache programmatically in Magento 2. It will be useful for you in your custom module or new feature.
Whenever you make any modifications to your Magento website, you will need to flush cache to see the changes. And as you may know, there are some ways to do that.
- Go to System -> Tools -> Cache Management then select Flush Magento Cache
- Remove var/cache directory using File Manager in cPanel, FTP or SSH
- Using code ( helpful for automation )
In Magento 1
1 2 3 4 5 |
Mage::app()->cleanCache(); or Mage::app()->getCacheInstance()->flush(); |
In Magento 2
-
Define constructor
1 2 3 4 5 6 7 8 9 |
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; } |
-
Create a function to flush magento cache
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
public function flushCache(){ $types = array('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(); } } |
You can edit $types variable if you don’t want to clear all cache types.
Using above code, we can clear Magento cache instead of using magento admin panel or removing var/cache folder. If you need any assitance, leave us a message