What is IdentityInterface in Magento2
From what I understood, this is kind of the equivalence of the getCacheTags
method of Magento 1.
The getIdentities
from model classes is then used in every block class referencing this model.
Ok let's take the /Magento/Catalog/Model/Category.php
:
public function getIdentities()
{
$identities = [
self::CACHE_TAG . '_' . $this->getId(),
];
if ($this->hasDataChanges() || $this->isDeleted()) {
$identities[] = Product::CACHE_PRODUCT_CATEGORY_TAG . '_' . $this->getId();
}
return $identities;
}
This method is then referenced in /Magento/Catalog/Block/Category/View.php
:
public function getIdentities()
{
return $this->getCurrentCategory()->getIdentities();
}
In M2, you now have to declare the cache tag with the getIdentities
method at the model level, then you can use it in blocks referencing those models.
If you check every block implementing the getIdentities
method, they all reference a corresponding model getIdentities
method or a corresponding model cache tag such as \Magento\Catalog\Model\Product::CACHE_TAG
Then those block getIdentities
methods are used in Varnish for caching reasons as mentioned by Matthéo to set the X-Magento-Tags
header.
This header is then used in Magento/Framework/App/PageCache/Kernel.php
in the process()
method to save the cache:
$tagsHeader = $response->getHeader('X-Magento-Tags');
$tags = $tagsHeader ? explode(',', $tagsHeader->getFieldValue()) : [];
$response->clearHeader('Set-Cookie');
$response->clearHeader('X-Magento-Tags');
if (!headers_sent()) {
header_remove('Set-Cookie');
}
$this->cache->save(serialize($response), $this->identifier->getValue(), $tags, $maxAge);
Judging by the class Magento\Framework\DataObject\IdentityInterface
comment it is used for cache and make a unique entity ID that is used in Varnish ESI headers in vendor/magento/module-page-cache/Controller/Block/Esi.php
line 28.
if ($blockInstance instanceof \Magento\Framework\DataObject\IdentityInterface) {
$response->setHeader('X-Magento-Tags', implode(',', $blockInstance->getIdentities()));
}
The IdentityInterface will force Model class to define the getIdentities() method which will return a unique id for the model. You must only use this interface if your model required cache refresh after database operation and render information to the frontend page.