Menu Close
    Hire us Request quote Reading list Switch to dark mode

    How to clean and flush cache programmatically in magento2

    How to clean and flush cache programmatically in magento2 – Having issue with cache clear programmatically in magento2, then no need to worry about this . The solution is here, you can easily add this cache clean/flush code to your project by following just some easy steps-

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

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

    . . .

    Comments (2)

    Add Your Comment

  • Monika Tadvi
    Thank you. This code is working for me.
  • Mitch Thompson
    Shouldn’t you use generated factories and not the actual objects?

    public function __construct(
    MagentoFrameworkAppCacheManagerFactory $cacheManagerFactory)
    {
    $this->cacheManagerFactory = $cacheManagerFactory;
    }

    public function clearCache() {
    $cacheManager = $this->cacheManagerFactory->create();
    $types = $cacheManager->getAvailableTypes();
    $cacheManager->clean($types);
    }

  • Back to Top
    css.php
    Hire Us!
    Brief us about your requirements and we'll get back to you.
    Woo! Hooy!
    We have just received your message and our expert will get back to you shortly.
    Send Again
    Close