Let’s see how we can Store & Retrieve From The Custom Cache
We have created a custom cache type in the post-https://sbdevblog.com/magento-2-how-to-create-custom-cache/. Let’s see How we can save data to the custom cache and How we can retrieve data from the cache.
Magento 2: Store & Retrieve From The Custom Cache
The cache is used as storage to improve page speed. So In order to improve performance, Magento 2 stores data in the cache. We also can save our data to the custom cache.
Store Data To The Custom Cache
<?php
namespace SbDevBlog\Cache\Services;
use Magento\Framework\App\CacheInterface;
use Magento\Framework\Serialize\SerializerInterface;
class SaveDataToCustomCache
{
/**
* @var CacheInterface
*/
private CacheInterface $cache;
/**
* @var SerializerInterface
*/
private SerializerInterface $serializer;
public function __construct(
CacheInterface $cache,
SerializerInterface $serializer
){
$this->cache = $cache;
$this->serializer = $serializer;
}
/**
* Save data to the cache
*
* @param array $data
* @param int $cacheLifeTime
* @return void
*/
public function saveDataToCache(array $data = [], int $cacheLifeTime = 86400): void
{
$this->cache->save(
$this->serializer->serialize($data),
"cache-identifier",
["cache-tags"],
$cacheLifeTime
);
}
}
It is so simple to save data to the cache. Let’s see how we can retrieve data from the cache.
How to retrieve data from the cache.
<?php
namespace SbDevBlog\Cache\Services;
use Magento\Framework\App\CacheInterface;
use Magento\Framework\Serialize\SerializerInterface;
class SaveDataToCustomCache
{
private const CACHE_LIFE_TIME = 86400;
/**
* @var CacheInterface
*/
private CacheInterface $cache;
/**
* @var SerializerInterface
*/
private SerializerInterface $serializer;
public function __construct(
CacheInterface $cache,
SerializerInterface $serializer
){
$this->cache = $cache;
$this->serializer = $serializer;
}
/**
* Get Data From Cache
*
* @return array|bool|float|int|string|null
*/
public function getDataFromCache(): float|int|bool|array|string|null
{
if($this->cache->load("cache-identifier")) {
return $this->serializer->unserialize(
$this->cache->load("cache-identifier")
);
}
return [];
}
}
That’s it. We can easily save and get the data from the cache. Thanks for reading sbdevblog. Please use the comment box for your feedback.
Check out the post to invalidate and flush the cache https://sbdevblog.com/magento-2-how-to-invalidate-and-flush-custom-cache-type/
Note: Please verify the code of this blog and the relevant git repository before using it in production.
🙂 HAPPY CODING 🙂
2 thoughts on “Magento 2: Store & Retrieve From The Custom Cache”