Magento使用缓存,无法序列化集合



我正在学习如何使用 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必须打开",然后我收到一条消息说出于安全原因无法激活它。

然后我尝试序列化,就像上面的代码所示,但它也不起作用。似乎 magento 保护集合不被序列化,因为它们可能非常大。

所以最后我试图在序列化serialize(urlencode($categories))urldecode(unserialize($categories))之前urlencode(),但我得到了字符串"N;"使用此 aproach 和反序列化时的空字符串。

我正在使用magento 1.9.3,我遵循了此文档和之前的问题:

https://www.nicksays.co.uk/developers-guide-magento-cache/

http://inchoo.net/magento/magento-block-caching/

Magento:缓存集合上的序列化错误

Magento 如何缓存产品集合

还有一些关于这个问题的其他问题,但也许没有必要写太多链接,我不想垃圾邮件。

编辑:如果取而代之的是我使用类似数组的集合

$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))一样简单

最新更新