Your destination for complete Tech news

how to save data in the cache in Magento 2

821 0
2 min read

In Magento 2, caching is an important aspect to optimize the performance of your online store. Magento 2 provides a built-in caching mechanism that allows you to cache various types of data, including configuration, layout, blocks, and more. To save data in cache in Magento 2, you can use the Cache Manager.

Here’s a general guide on how to save and retrieve data in the cache in Magento 2:

Save Data in Cache:

Inject Cache Manager in your class:

In your class, you can inject the \Magento\Framework\App\Cache\TypeListInterface and \Magento\Framework\App\Cache\Frontend\Pool instances to manage the cache.

protected $cacheTypeList;
protected $cacheFrontendPool;

public function __construct(
    \Magento\Framework\App\Cache\TypeListInterface $cacheTypeList,
    \Magento\Framework\App\Cache\Frontend\Pool $cacheFrontendPool
) {
    $this->cacheTypeList = $cacheTypeList;
    $this->cacheFrontendPool = $cacheFrontendPool;

Save Data in Cache:

You can save data in the cache using the cache manager. Here’s an example:

public function saveDataInCache($data)
    $cacheType = 'your_custom_cache_type'; // Change this to a unique identifier for your cache

    // Invalidate the cache type to make sure the new data is picked up

    // Clean the invalidated cache type

    // Save data in cache
    $cacheFrontend = $this->cacheFrontendPool->get($cacheType);
    $cacheFrontend->save($data, 'cache_key', [$cacheType], 0);

    return $data;

Retrieve Data from Cache:

You can retrieve data from the cache using the cache manager. Here’s an example:

public function getDataFromCache()
    $cacheType = 'your_custom_cache_type'; // Same identifier used during saving

    $cacheFrontend = $this->cacheFrontendPool->get($cacheType);
    $cachedData = $cacheFrontend->load('cache_key');

    if ($cachedData) {
        // Data found in cache
        return $cachedData;
    } else {
        // Data not found in cache, fetch it from the source and save it again
        $data = $this->fetchDataFromSource();
        return $data;

Remember to replace 'your_custom_cache_type' and 'cache_key' with your own cache type identifier and cache key.

Please note that caching should be used judiciously, and you need to manage cache invalidation appropriately to ensure that the data in the cache is always up to date.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.