Magento 2 provide good cache mechanism for faster serving pages to browser. Sometimes we require to clean cache by tag id as per custom requirement. In recent projects there was custom requirement in which customer want to clear cache for particular cms page only after save it. So i did it in detail and found better solution for clear cache for cms page , catalog product , catalog category and even you can clear cache for custom module also.
In this article i will explain how you can identify tag for clear cache for particular area of magento site. Cache id is used to identify a specific cache record. If you save something in the cache you can later retrieve it by its id. First of all you need to find proper CACHE_ID and CACHE_TAG. You can find it easily by opening particular model.
For example if you open “vendor/magento/module-catalog/Model/Product.php” then you will see kind of below code :
These tags are used for clear cache by tags.
So now let see how can we clean caches partially with tags, private $fullPageCache; private function getCache() { if (!$this->fullPageCache) { $this->fullPageCache = \Magento\Framework\App\ObjectManager::getInstance()->get( \Magento\PageCache\Model\Cache\Type::class ); } return $this->fullPageCache; } public function cleanByTags() { $productId = 21; //Id of the Product whose Cache need to be cleaned $tags = ['CAT_P_'.$productId]; $this->getCache()->clean(\Zend_Cache::CLEANING_MODE_MATCHING_TAG, $tags); }
Click one of our contacts below to chat on WhatsApp