[英]Magento work with cache, can't serialize collection
我正在學習如何使用 magento 緩存,但在嘗試序列化集合時遇到了一些困難。
其實這是我的代碼:
class Feliu_Featuredcategories_Block_Topcategories extends Mage_Core_Block_Template
{
protected function _construct()
{
$storeId = Mage::app()->getStore()->getId();
$this->addData(array(
'cache_lifetime' => 3600,
'cache_tags' => array(Mage_Catalog_Model_Product::CACHE_TAG),
'cache_key' => 'homepage-most-view-' . $storeId,
));
}
public function setData()
{
$storeId = Mage::app()->getStore()->getId();
$cache = Mage::app()->getCache();
$key = 'homepage-most-view-' . $storeId;
$cached_categories = $cache->load($key);
if (! $cached_categories) {
$categories = Mage::getModel('catalog/category')
->getCollection()
->addAttributeToSelect(array('data', 'name', 'add_to_top_categories'))
->addAttributeToFilter('add_to_top_categories', array('eq' => '1'));
$categories->load();
$cache->save(serialize($categories), $key);
} else {
$categories = unserialize($cached_categories);
}
return $categories;
}
}
起初我嘗試$cache->save($categories, $key);
直接,但我讀到不能直接保存集合,並且我收到一條錯誤消息:'automatic_serialization must be on' 當我嘗試將 automatic_serialization 設置為 true 然后我收到一條消息說它不能被激活以確保安全原因。
然后我嘗試序列化,就像上面的代碼顯示的那樣,但它也不起作用。 似乎 magento 保護集合不被序列化,因為它們可能非常大。
所以最后我在序列化serialize(urlencode($categories))
和urldecode(unserialize($categories))
之前嘗試了urlencode()
urldecode(unserialize($categories))
但我得到了字符串"N;"
在反序列化時使用這種方法和空字符串進行序列化。
我使用的是 magento 1.9.3,我遵循了這個文檔和以前的問題:
https://www.nicksays.co.uk/developers-guide-magento-cache/
http://inchoo.net/magento/magento-block-caching/
Magento 如何緩存 productCollection
還有其他一些關於這個的問題,但也許沒有必要寫太多鏈接,我不想垃圾郵件。
編輯:如果不是一個集合,我使用一個數組
$categories = array('banana', 'apple', 'kiwi', 'strawberry', 'pomelo', 'melon');
那么代碼似乎可以正常工作
最后我解決了它,答案比開始時更簡單,但我寫在這里是因為它可能會對將來的某人有所幫助。
由於無法緩存或序列化集合,因此我使用集合中所需的數據創建了一個數組。
$categories = Mage::getModel('catalog/category')
->getCollection()
->addAttributeToFilter('add_to_top_categories', array('eq' => '1'))
->addAttributeToSelect(array('data', 'name'));
我讓集合只添加我需要的字段,並選擇我想要的數據。
$array = array();
foreach ($categories as $_category)
{
array_push($array, array('url' => $_category->getUrl(), 'name' => $_category->getName()));
}
現在我創建了一個數組,其中包含包含我想要的數據的對象。 下一步是序列化我剛剛制作的數組並將其保存在緩存中。
$cache->save(serialize($array), $key, array('custom_home_cache'), 60*60);
並檢索數據就像$cache->load(unserialize($key))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.