2013-03-14 59 views
6

我注意到我的主頁花了很長時間來加載 - 根據site24x7.com超過6秒infact,所以我一直在切換元素來試圖確定是什麼原因,並且它已經關閉至2個產品收集文件,我已展示新產品和暢銷產品。Magento如何緩存一個productCollection

只要我從主頁中刪除這些,頁面加載時間就會少於0.5秒。

那麼,任何人都可以幫助優化和緩存productCollection?我有服務器上安裝和運行的APC,但林不知道它緩存位於應用程序/設計/前端/默認/ MY_THEME /目錄/產品/ newproducts.phtml

因此,我收集要求暢銷(實際上大多數觀看)看起來像這樣;

<?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) 
    ?> 

我該如何進一步優化?

回答

7

嘗試

$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)); 
} 

+0

謝謝,正是一種英特爾的我了! – 2013-03-14 15:35:44

+0

@ R.S你爲什麼使用'urlencode'兩次?這裏有必要還是它是一個bug?不應該是這樣的:'$ data = urlencode(serialize($ array)); $ cache-> save($ data,$ key,array(「homepage_cache」),60 * 60 * 24);'? – zitix 2014-03-25 18:18:10

+0

這是一個錯字..現在修復 – 2014-03-25 20:49:32

0

如果你希望緩存$收藏,已經有一個內置的可能性集合中的緩存Magento的。

$_productCollection= Mage::getResourceModel('reports/product_collection'); 

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

信用卡上面的代碼:apiworks.net(http://www.apiworks.net/2015/01/magento-collection-caching.html

+0

我理解頂層是如何設置的。但有沒有邏輯,我們需要實現第二次運行,以檢查緩存是否存在,然後將其保存到緩存......或者「緩存知道/做這個有自己的」thhx! – 2017-01-27 18:26:05

+0

嗨,@ snh_nl。正如你在下面的代碼中看到的那樣,它是Varien_Data_Collection_Db類的一部分:http://collabshot.com/show/H0q3bn Magento首先嚐試從緩存中加載,然後如果失敗,它從數據庫加載並保存緩存版本。 所以,答案是:對於同一個$ collection對象,使用上面的代碼初始化緩存後,不需要執行任何操作。它會自動下次爲您加載。 – 2017-02-02 08:51:03

+0

我們可以在html模板文件中使用像https://gist.github.com/seansan/1397a892fa496d5b5f98c2d85e4fa82e這樣的代碼嗎?或者,如何在phtml文件中緩存集合調用(例如產品列表) – 2017-02-02 13:30:44