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

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;
    }
}
1
  • Thank you So much @Tokey Tu, its working fine. Jul 9 at 12:15

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.