【发布时间】:2017-03-08 20:24:52
【问题描述】:
我正在学习如何使用 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设置为true时收到一条错误消息:“automatic_serialization must be on”然后我收到了消息说出于安全原因无法激活它。
然后我尝试序列化,正如上面的代码所示,但它也没有工作。似乎 magento 可以保护集合不被序列化,因为它们可能非常大。
所以最后我在序列化serialize(urlencode($categories)) 和urldecode(unserialize($categories)) 之前尝试了urlencode(),但是我得到了使用这种方法序列化的字符串"N;",并且在反序列化时得到了一个空字符串。
我使用的是 magento 1.9.3,我遵循了这个文档和之前的问题:
https://www.nicksays.co.uk/developers-guide-magento-cache/
http://inchoo.net/magento/magento-block-caching/
Magento: serialization error on caching Collection
Magento how to cache a productCollection
还有一些关于这个的其他问题,不过可能没必要写太多链接,我不想发垃圾邮件。
编辑:如果不是一个集合,我会使用类似的数组
$categories = array('banana', 'apple', 'kiwi', 'strawberry', 'pomelo', 'melon');
那么代码似乎可以正常工作
【问题讨论】:
标签: magento magento-1.9