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?

1 Answer 1


Add the caching interface loading to the constructor.

public function __construct(
   Magento\Framework\DataObjectFactory $dataObjectFactory,
   Magento\Framework\App\CacheInterface $cache,
   Magento\Framework\Serialize\Serializer\Json $serializer
) {
   $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


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

  • 1
    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, 2019 at 12:54
  • Got your point, thank @Marius
    – Saphal Jha
    May 2, 2019 at 13:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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