0

I need to flush cache when a controller is loaded. This is mandatory for me because some function works only when cache is cleared. I Hope will get help.

  • it is not good idea to flush cache on controller hit.Can u please tell which function is not working when cache is enabled? – Amit Bera Dec 20 '17 at 7:28
  • I need to show a value from database. When db is updated the value in frontend is not updating. It is updating when cache is flushed alone. – Ramesh KR Dec 20 '17 at 7:29
  • 1
    Can u please share the code which you have tried and where you face the issues? – Amit Bera Dec 20 '17 at 8:56
  • $suser_id = $this->getCustomerId(); $this->_resources = \Magento\Framework\App\ObjectManager::getInstance()->get('Magento\Framework\App\ResourceConnection'); $connection= $this->_resources->getConnection(); $sql = "SELECT money FROM total_cashback WHERE user_id = '$suser_id' "; $result = $connection->fetchall($sql); @$total = $result['0']; $totalmoney = $total['money']; return $totalmoney; – Ramesh KR Dec 22 '17 at 8:01
  • In this code I'm getting table value but when table value is updated it is not updating in frontend until cache clearence – Ramesh KR Dec 22 '17 at 8:02
2

1. Define constructor – pass Magento\Framework\App\Cache\TypeListInterface and Magento\Framework\App\Cache\Frontend\Pool to your file’s constructor as defined below :

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;
}

2. Now add following code to the method where you want clear/flush cache

$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();
}
  • I used this in block function but cache is not cleaned when page is reloaded or loaded – Ramesh KR Dec 22 '17 at 8:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.