Magento how to cache productCollection

Ive noticed that my home page takes a long time to load - more than 6 seconds infact according to site24x7.com, so I included elements to try to determine the cause, and this is up to 2 product collection files I made to show new products and best-selling products.

As soon as I remove them from the main page, the page loads in less than 0.5 seconds.

So, can anyone help with optimizing and caching productCollection? I have APC installed and running on the server, but I'm not sure that it caches files located in app / design / frontend / default / MY_THEME / catalog / product / newproducts.phtml

So my call to collect the best-selling (most-watched in fact) is as follows:

<?php $storeId = Mage::app()->getStore()->getId(); // return current store id ?> <?php $_productCollection= Mage::getResourceModel('reports/product_collection') ->addAttributeToSelect('*') ->addStoreFilter($storeId) ->addViewsCount() ->addFieldToFilter('visibility', Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH) ->addFieldToFilter('status',Mage_Catalog_Model_Product_Status::STATUS_ENABLED); $_productCollection->getSelect()->limit(8) ?> 

How can I optimize this?

+6
source share
2 answers

Try

  $storeId = Mage::app()->getStore()->getId(); $cache = Mage::getSingleton('core/cache'); $key = 'homepage-most-view-' . $storeId; if(! $data = $cache->load($key)){ $_productCollection= Mage::getResourceModel('reports/product_collection') ->addAttributeToSelect('*') ->addStoreFilter($storeId) ->addViewsCount() ->addFieldToFilter('visibility', Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH) ->addFieldToFilter('status',Mage_Catalog_Model_Product_Status::STATUS_ENABLED); $_productCollection->getSelect()->limit(8) // get the element you need from $_productCollection and store in $array $data = serialize($array); $cache->save(urlencode($data), $key, array("homepage_cache"), 60*60*24); } else{ $data = unserialize(urldecode($data)); } 

Cm.

+7
source

If you want to cache $ collection, there is already a built-in ability to cache collections in Magento.

  $_productCollection= Mage::getResourceModel('reports/product_collection'); $cache = Mage::app()->getCache(); //Let get cache instance $cache->setLifetime(86400); //Here we set collection cache lifetime $_productCollection->initCache( $cache, 'Bestsellers_', //this is just custom prefix array('collections') ); } 

Credit for the above code: apiworks.net ( http://www.apiworks.net/2015/01/magento-collection-caching.html )

0
source

All Articles