Magento中为Block启用Cache

本文介绍了一种在Block类中实现缓存优化的方法,通过构造唯一的cache_key并利用Magento框架的功能来提高系统的性能。该方法包括设置缓存生命周期、缓存标签,并通过序列化和反序列化来存储和读取数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在Block类的_construct(不是构造方法)方法中加入以下代码:

public function _construct()
{
$this->addData(
array(
'cache_lifetime' => 3600,
'cache_tags' => array(Mage_Catalog_Model_Product::CACHE_TAG),
'cache_key' => 'productfaq_'.Mage::registry('product')->getId().'_'.Mage::app()->getStore()->getId()
. '_' . Mage::getDesign()->getPackageName()
. '_' . Mage::getDesign()->getTheme('template')
. '_' . Mage::getSingleton('customer/session')->getCustomerGroupId()
)
);

parent::_construct();
}

cache_key必须唯一。
在获得数据的方法中加入:

$faq_data = @unserialize( Mage::app()->loadCache($this->getCacheKey()) );
//从数据库取出数据并存入到faq_data 中
if (!$faq_data) {

$faq_data = array();
...
$faq_data[]=array('customer_id' => $customerId,
'name' => $sName,
'avatar' => $sAvatar,
'question' => $sQuestion,
'answer' => $sAnswer,
);

}
Mage::app()->saveCache(serialize($faq_data), $this->getCacheKey(), $this->getCacheTags(),$this->getCacheLifetime());
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值