0

I have a requirement where, I have huge custom data(around 5000) to display in a page. Currently, I have displayed them in a table and it takes time when I load the page. I want to save the collection in cache and retrieve data from cache. SO that it will load faster. Later on I want to implement filter on cached collection.

Anyone who can help me to implement cache in my requirement?

0

Add the caching interface loading to the constructor.

public function __construct(
   Magento\Framework\DataObjectFactory $dataObjectFactory,
   Magento\Framework\App\CacheInterface $cache,
   Json $serializer = null
) {
   $this->dataObjectFactory = $dataObjectFactory;
   $this->cache = $cache;
   $this->serializer = $serializer;
}

For saving the data in the cache

$this->cache->save($data, $identifier, $tags, $lifeTime);

If you want to save in the array, you need to use the serializer.

$data = $this->serializer->unserialize($data) 

$identifier - unique identifier of the stored information block.

$tags = array of tags - may be empty.

$lifeTime - (in seconds) - by default null, it always appears in the cache and valid.

To get data from the cache

$this->cache->load($identifier)

If there is no data or the lifetime has expired, the method returns false.

Convert the data after receiving it from the cache, if you have it serialized before adding

  • why do you need to make the serializer null in the constructor and then instantiate it via object manager? This is done in the core just for backwards compatibility when a new parameter is added to the constructor. But in your own code you don't need it. You can just leave in the constructor signature Json $serializer and in the method $this->serializer = $serializer – Marius May 2 at 12:54
  • Got your point, thank @Marius – Saphal Jha May 2 at 13:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.