0

Hi am having a controller Search.php every time I do operation it loads all the collection and takes much time to load. So I wanted to cache the custom collection and optimize the loading time. this is my collection how to put this in a cache. below is my controller

use Magento\Framework\Serialize\SerializerInterface;

class Search extends \Magento\Framework\App\Action\Action
{
    private cacheId = 'IdForCachingPurposes';
    private $serializer;
    
    public function __construct(
        SerializerInterface $serializer,
        array $data = []
    ) {
        parent::__construct($context, $data);
        $this->serializer   = $serializer;
    }

    public function execute()
    {
        $writer = new \Zend\Log\Writer\Stream(BP . '/var/log/PRAVEEN.log'); 
        $logger = new \Zend\Log\Logger(); $logger->addWriter($writer); 

        $collection = "My data";
        if($this->cache->load($this->cacheId)) {
            $logger->info('cached'); 

            //Get unserialized data from Cache
            $data = unserialize($this->cache->load($this->cacheId));
        } else {
            $logger->info('cach saved'); 

            //Store Data in Cache
            $storeData = $this->cache->save(
            serialize($collection), $this->cacheId, array(\Vendor\Search\Model\Cache\Type::CACHE_TAG), 
            86400);
        }
    }
}

Where am doing wrong. Can I get Help? Thank yo

1 Answer 1

2

Please try the following code:

use Magento\Framework\App\Action\Context;
use Magento\Framework\App\CacheInterface;
use Psr\Log\LoggerInterface;

class Search extends \Magento\Framework\App\Action\Action
{
    protected $cache;

    protected $logger;

    public function __construct(
        Context $context,
        CacheInterface $cache,
        LoggerInterface $logger
    )
    {
        $this->cache = $cache;
        $this->logger = $logger;
        parent::__construct($context);
    }

    public function execute()
    {
        $cacheId = 'IdForCachingPurposes';
        $testData = "My data";

        if ($cacheData = $this->cache->load($cacheId)) {
            $cacheData = unserialize($cacheData);
            $this->logger->info('---Get Cache Data---');
            $this->logger->info($cacheData);
            return $cacheData;
        }
        $this->logger->info('---Save Cache Data---');
        $this->logger->info($testData);
        $this->cache->save(serialize($testData), $cacheId, [], 86400);
        return $testData;
    }
}
2
  • Thank you So much @Tokey Tu, its working fine. Commented Jul 9, 2021 at 12:15
  • How do you clear the cacheId when the cache is cleaned?
    – dreid
    Commented Feb 16, 2023 at 15:58

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.