DEV Community

Yegor Shytikov
Yegor Shytikov

Posted on

Magento 2 cache element on a page (block) by store id

Magento 2 has several ways to cache the block.

Cacheable Block
In case, cache_lifetime of the block is set to a number greater than 0, the block is cacheable (for block cache).

When To Use
You should use the cacheable block in the following situations:

The block is frequently used. For example, the same block with the same content is shown on several pages.
The block is a cacheable part of the non-cacheable page.
How To Use
Take the following actions to use the cacheable block:

Setting cache_lifetime via layout XML:

<block class="MyBlock">
    <arguments>
        <argument name="cache_lifetime" xsi:type="number">3600</argument>
    </arguments>
</block>
Enter fullscreen mode Exit fullscreen mode

Setting cache_lifetime via DI configuration:

<type name="MyBlock">
    <arguments>
        <argument name="data" xsi:type="array">
            <item name="cache_lifetime" xsi:type="number">3600</item>
        </argument>
    </arguments>
</type>
Enter fullscreen mode Exit fullscreen mode

Setting cache_lifetime wondrously in imperative way:

$block->setCacheLifetime(3600);
// or
$block->setData('cache_lifetime', 3600);
Enter fullscreen mode Exit fullscreen mode

Overriding retriever method (often used in core modules for some reasons):

class MyBlock extends AbstractBlock
{
    protected function getCacheLifetime()
    {
        return 3600;
    }
}
Enter fullscreen mode Exit fullscreen mode

it will cache content globally for the entire Magento 2 store.

You can add cache key to cache by Store ID:



<?php

namespace My\Something\Block\Name;

use Magento\Cms\Block\Block;
use Magento\Framework\View\Element\Context;
use Magento\Cms\Model\Template\FilterProvider;
use Magento\Store\Model\StoreManagerInterface;
use Magento\Cms\Model\BlockFactory;

class MyBlock extends Block
{
    /**
     * @var int
     */
    private $blockId;

    /**
     * @var Config
     */
    private $configProvider;

    public function __construct(
        Context $context,
        FilterProvider $filterProvider,
        StoreManagerInterface $storeManager,
        BlockFactory $blockFactory,
        array $data = []
    ) {
        parent::__construct($context, $filterProvider, $storeManager, $blockFactory, $data);
    }

    /**
     * Cache block by Store ID
     */
    public function getCacheKeyInfo()
    {
        return array_merge(parent::getCacheKeyInfo(), ['store' . $this->_storeManager->getStore()->getId()]);
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)