Reading list Switch to dark mode

    How to clean and flush cache programmatically in magento2

    Updated 4 March 2024

    How to clean and flush cache programmatically in magento2 – Sometimes it is required to clear the cache after performing an operation from the user’s end to reflect the changes or take effect on the UI. But we can not expect the end user to run the CLI commands from the terminal to clear the cache. As we are expecting the user as a non – technical individual, so for the fluency of the application we may need to clear the cache programmatically on the behalf of the user to enhance the user experience . If you are having issue with cache clear programmatically in magento2, then you don’t need to worry about this anymore . The solution is in this blog, you can easily follow the below steps and add this cache clean/flush code to your project by following just some easy steps-

    Here, I am assuming that you are already aware of how to create a custom module in magento 2 and Controllers and Helpers to the module.

    1. Define constructor in you Controller or Helper – In the constructor you need to pass two arguments i.e. 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();
    }

    How to clean and flush cache programmatically in magento2

    Searching for an experienced
    Magento 2 Company ?
    Find out More

    So in this way you can clean and flush cache in magento2 . Hope this blog will help you.

    If you have any queries please comment below for discussion

    You can also check the below links :

    https://webkul.com/blog/flush-cache-by-tag-in-magento-2/

    https://devdocs.magento.com/guides/v2.3/config-guide/cli/config-cli-subcommands-cache.html

    . . .

    Leave a Comment

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


    2 comments

  • Monika Tadvi
  • Mitch Thompson
  • Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home