【问题标题】:Magento work with cache, can't serialize collectionMagento 使用缓存,无法序列化集合
【发布时间】: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


    【解决方案1】:

    最后我解决了它,答案比我一开始的时候最简单,但我写在这里是因为它可能会在将来对某人有所帮助。

    由于无法缓存或序列化集合,因此我使用集合中需要的数据创建了一个数组。

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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-09
    • 2014-07-02
    • 1970-01-01
    相关资源
    最近更新 更多