Magento 2: how to create your own custom cache type?
-
14-04-2021 - |
문제
In Magento 1, it was possible to create your own cache type by declaring the following in your config.xml
:
<global>
<cache>
<types>
<custom translate="label,description" module="module">
<label>Custom Cache</label>
<description>This is my custom cacge</description>
<tags>CUSTOM_CACHE_TAG</tags>
</custom >
</types>
</cache>
</global>
It will result in a new cache type added to the backend under System > Cache Management and thus, it will add the ability to flush cache related to the CUSTOM_CACHE_TAG
cache tag.
Is that possible in M2 and how to achieve it ?
해결책
This is below some basic structure for create custom cache type,
create one module with,
app/code/Vendor/Cachetype/etc/cache.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Cache/etc/cache.xsd">
<type name="custom_cache" translate="label,description" instance="Vendor\Cachetype\Model\Cache\Type">
<label>Custom Cache type</label>
<description>Custom cache description.</description>
</type>
</config>
app/code/Vendor/Cachetype/i18n/en_US.csv
"Custom cache description.","Custom cache description."
"cachetype","Cache type"
app/code/Vendor/Cachetype/Model/Cache/Type.php
<?php
namespace Vendor\Cachetype\Model\Cache;
/**
* System / Cache Management / Cache type "Custom Cache Tag"
*/
class Type extends \Magento\Framework\Cache\Frontend\Decorator\TagScope
{
/**
* Cache type code unique among all cache types
*/
const TYPE_IDENTIFIER = 'custom_cache_tag';
/**
* Cache tag used to distinguish the cache type from all other cache
*/
const CACHE_TAG = 'CUSTOM_CACHE_TAG';
/**
* @param \Magento\Framework\App\Cache\Type\FrontendPool $cacheFrontendPool
*/
public function __construct(\Magento\Framework\App\Cache\Type\FrontendPool $cacheFrontendPool)
{
parent::__construct($cacheFrontendPool->get(self::TYPE_IDENTIFIER), self::CACHE_TAG);
}
}
Thanks.
다른 팁
Would like to edit Rakesh accepted comment, but was rejected....
Anyway here some modifications, additional info to the good answer from Rakesh:
The cache.xml needs to be modfied a little:
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Cache/etc/cache.xsd">
<type name="custom_cache_tag" translate="label,description" instance="Vendor\Cachetype\Model\Cache\Type">
<label>Custom Cache type</label>
<description>Custom cache description.</description>
</type>
</config>
So the the name must match the cache_tag.
How to use it, look here: Using Magento 2 custom cache in custom module
To use the data (after being cached) you have to unserialize it:
$data = unserialize($this->_cacheType->load($cacheKey));
This blog states step by step guide for Custom Caching in Magento2