0

Like I mentioned in my question I am having a problem with cleaning/flushing cache on category/product pages.

I get some code, probably for some older version of Magento but didn't work.

Here it is:

    $cacheTag = \Magento\Catalog\Model\Category::CACHE_TAG . '_' . $catId;
    $category = $this->categoryRepository->get($catId, $this->storeManager->getStore()->getId());

    $this->cacheManager->clean(\Zend_Cache::CLEANING_MODE_MATCHING_ANY_TAG, [$cacheTag]);
    $this->eventManager->dispatch('clean_cache_by_tags', ['object' => $category]);

The same example I found here:

https://magecomp.com/blog/clear-cache-for-specific-cms-page-programmatically-in-magento-2/

I check Manager class and method clean have only one parameter(argument) and this is an array of types. So I tried with one argument and I get one error: Notice: Undefined index: instance in /app/vendor/magento/framework/App/Cache/TypeList.php online 75

So is there any other way how to clean cache on the category or product page?

Tnx for the help.

1 Answer 1

0

You can use this code :

<?php
namespace Vendor\Extension\Block;

use Magento\Framework\App\PageCache\Version;
use Magento\Framework\App\Cache\TypeListInterface;
use Magento\Framework\App\Cache\Frontend\Pool;

class YOURBLOCKCLASS 
{

    protected $cacheTypeList;
    protected $cacheFrontendPool;
 
    public function __construct(TypeListInterface $cacheTypeList, 
    Pool $cacheFrontendPool)
    {
    
        $this->cacheTypeList = $cacheTypeList;
        $this->cacheFrontendPool = $cacheFrontendPool;
    }
 
    public function MyCustomcacheFunction()
    {
       $_types = [
            '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();
        }
    }
}

Now call your Block function by creating the object of block class where you want to do the caching.

2
  • Thank you for response. This code will clean/flush all categories or just categories that I want? I need clean/flush just few of them (i am saving category_id in database table and then within foreach I am trying clean/flush cache with cache tag cat_c_id ). Oct 28, 2021 at 5:57
  • then you can pass the category id on function call and check if you want to perform for that one or not. Oct 28, 2021 at 6:08

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.