Previously, we have discussed how to clean & flush cache in Magento 2. In today's article, this topic will be continued by going through "How to save data to cache in Magento 2". Let's dive right in!
What is Magento cache?
Caching is one of the most effective ways to improve website performance. In essence, Magento retrieves stored (cached) content from a previous request for the same client instead of requesting files from your server every time someone visits your site is a more efficient use of network bandwidth. By default, Magento supports a lot of cache types out of the box, you can refer to this topic to get an understanding of them.
How does Magento work with the caching system?
Caching system should be followed these steps:
- Step 1: At the first call to get content data, Magento uses the identifier key to check the caching system if the content data has been cached, it will return to Step 3. And if the one hasn't been cached yet, it will get and process data as normal then return to Step 2.
- Step 2: The processed data will be converted to serialize string, saved to Magento caching system (it could save to files, database … depend on configuration), and marked with an identifier key
- Step 3: Unserialize content data from Caching system and return it
After the data is cached, the data that will be retrieved from the Caching system is the processed data. But because it skips the step of fetching from the database, processing by Magento should help the system run faster.
For more information, we will let you know in the below example. In this example we will create a custom cache type then store data and load them:
Create a custom cache type and save data to cache in Magento 2
Step 1: Initialize a custom cache type
- Declare a new cache type in the Magenest/CacheExample/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="magenest_cache_type_id" translate="label,description" instance="Magenest\CacheExample\Model\Cache\Type\CacheType"> <label>Magenest Cache Type Label</label> <description>Magenest Cache Type Description</description> </type> </config>
- Create Cache type Model class Magenest\CacheExample\Model\Cache\Type\CacheType
<?php namespace Magenest\CacheExample\Model\Cache\Type; use Magento\Framework\App\Cache\Type\FrontendPool; use Magento\Framework\Cache\Frontend\Decorator\TagScope; /** * System / Cache Management / Cache type "Your Cache Type Label" */ class CacheType extends TagScope { /** * Cache type code unique among all cache types */ const TYPE_IDENTIFIER = 'magenest_cache_type_id'; /** * The tag name that limits the cache cleaning scope within a particular tag */ const CACHE_TAG = 'MAGENEST_CACHE_TYPE_TAG'; /** * @param FrontendPool $cacheFrontendPool */ public function __construct(FrontendPool $cacheFrontendPool) { parent::__construct( $cacheFrontendPool->get(self::TYPE_IDENTIFIER), self::CACHE_TAG ); } }
In which:
- magenest_cache_type_id defines the unique identifier of a cache type.
- MAGENEST_CACHE_TYPE_TAG defines the unique tag to be used in the cache type scoping.
After enabling the module, you will see a new cache type on the Cache Management page
Step 2: Store data to the custom cache type
The data will be saved to cache after getting it from the database and processing by Magento.
The following steps will store data to custom cache type:
- First of all, pass the argument Magento\Framework\App\CacheInterface $cache to the constructor of the class which you will use to store, load cached data
/** * @param \Magento\Framework\App\CacheInterface $cache * @param \Magento\Framework\Serialize\SerializerInterface $serializer */ public function __construct(\Magento\Framework\App\CacheInterface $cache, \Magento\Framework\Serialize\SerializerInterface $serializer) { $this->cache = $cache; $this->serializer = $serializer; }
In the function which processing data, save data after processing to the custom cache type:
$cacheKey = \Magenest\CacheExample\Model\Cache\Type\CacheType::TYPE_IDENTIFIER; $cacheTag = \Magenest\CacheExample\Model\Cache\Type\CacheType::CACHE_TAG; $storeData = $this->cache->save( $this->serializer->serialize($cacheData), $cacheKey, [$cacheTag], 86400 );
In which:
- $this->serializer->serialize($cacheData): data will be stored in Caching system
- $cacheKey: the unique identifier of a cache type
- [$cacheTag]: Array of strings, the cache record will be tagged by each string entry. This option provides more information about the cache record.
- 86400: lifetime of the cached data (second)
Step 3: Retrieve data from custom cache type
To get/load data from custom cache type, use the following code:
$cacheKey = \Magenest\CacheExample\Model\Cache\Type\CacheType::TYPE_IDENTIFIER; $data = $this->serializer->unserialize($this->cache->load($cacheKey));
Note:
- Cached data will expire at the end of lifetime or Administrator flush cache
- In this step, the data will be retrieved from the cache system, completely not processed or updated if the original data has been changed, so please set lifetime appropriately or flush cache after changing data.
Conclusion
We hope this article is useful to you and helps you learn more about how to save cache in Magento 2, leave us any questions if you have any issues during the process. Our store blog has tons of posts like this to help you grow your eCommerce business successfully, check it out!