Magento 2: Clean Cache by Cache Tags Programmatically

This article shows how you can clean cache by cache tags in Magento.


use Magento\Framework\App\CacheInterface;

class YourClassName
{
    /**
     * @var CacheInterface
     */
    protected $cache;

    /**
     ...
     * @param CacheInterface $cache
     */
    public function __construct(
        ...
        CacheInterface $cache
    ) {
        ...
        $this->cache = $cache;
    }

    /**
     * Clean Cache by Cache Tag
     *
     * @param array $cacheTags
     * @return bool
     */
    public function cleanCacheByTag($cacheTags)
    {
        return $this->cache->clean($cacheTags);
    }
}

The implementation of the \Magento\Framework\App\CacheInterface::clean function is in the class \Magento\Framework\App\Cache::clean.

Example:

In the below example, we pass an array of different cache tags and clean those particular cache tags.

The final cache tags of each entity are composed of the cache tag constant and the entity id.


$pageId = 2;
$blockId = 4;
$productId = 15;
$categoryId = 3;

$cacheTags = [
    \Magento\Cms\Model\Page::CACHE_TAG . '_' . $pageId,
    \Magento\Cms\Model\Block::CACHE_TAG . '_' . $blockId,
    \Magento\Catalog\Model\Product::CACHE_TAG . '_' . $productId,
    \Magento\Catalog\Model\Category::CACHE_TAG . '_' . $categoryId,
];

$this->cache->clean($cacheTags);

Each entity will have a unique cache tag.


\Magento\Cms\Model\Page::CACHE_TAG = cms_p 
\Magento\Cms\Model\Block::CACHE_TAG = cms_b
\Magento\Catalog\Model\Product::CACHE_TAG = cat_p 
\Magento\Catalog\Model\Category::CACHE_TAG = cat_b

Each of the above model pages has getIdentities() function which returns an array with the respective cache tag and the current entity id.

vendor/magento/module-cms/Model/Page.php


/**
 * Get identities
 *
 * @return array
 */
public function getIdentities()
{
    return [self::CACHE_TAG . '_' . $this->getId()];
}

Hope this helps. Thanks.