我有一个自定义模块,可以在我的产品页面上显示数据.我的模块需要获取当前的产品ID.我试过用:
Mage::registry('current_product');
Run Code Online (Sandbox Code Playgroud)
这适用于第一次加载,但是当我刷新时,current_product不再具有完整页面缓存的数据.
有任何想法吗?
Vin*_*nai 13
当整页缓存处理请求时(这样可以保持快速),不会调度目录产品操作控制器.因此,永远不会设置注册表变量.我假设您在完全缓存的页面上动态生成块.我的建议是尽量避免昂贵的负载,因为这会破坏整页缓存的速度提升.你真的想要尽可能地缓存块,即使它是每个客户和每个产品的单独缓存条目.
那就是说,这是怎么做的:
在容器中,实现_getIdentifier()方法:
protected function _getIdentifier()
{
return $this->_getCookieValue(Enterprise_PageCache_Model_Cookie::COOKIE_CUSTOMER, '');
}
Run Code Online (Sandbox Code Playgroud)
还要扩展_getCacheId()方法以包含方法_getIdentifier()的返回值和新的占位符属性:product_id
protected function _getCacheId()
{
return 'HOMEPAGE_PRODUCTS' . md5($this->_placeholder->getAttribute('cache_id') . ',' . $this->_placeholder->getAttribute('product_id')) . '_' . $this->_getIdentifier();
}
Run Code Online (Sandbox Code Playgroud)
接下来,在块类中,扩展方法getCacheKeyInfo().具有字符串索引的cache_key_info数组中的所有条目都在占位符上设置为属性.这就是我们如何将产品ID传递给占位符.
public function getCacheKeyInfo()
{
$info = parent::getCacheKeyInfo();
if (Mage::registry('current_product'))
{
$info['product_id'] = Mage::registry('current_product')->getId();
}
return $info;
}
Run Code Online (Sandbox Code Playgroud)
然后_saveCache()通过不在容器类中重写它并返回来启用该方法false.所以现在,因为容器从父类返回一个有效的id _getCacheId(),并且_saveCache()从父类继承,所以可以缓存该块,并以有效的方式应用于内容Enterprise_PageCache_Model_Container_Abstract::applyWithoutApp().
您可以通过使容器扩展Enterprise_PageCache_Model_Container_Customer而不是来设置缓存条目的生存期Enterprise_PageCache_Model_Container_Abstract.
如果仍然需要将product_id传递给块(即使它现在已缓存),您可以在_renderBlock()容器的方法中执行此操作:
protected function _renderBlock()
{
$blockClass = $this->_placeholder->getAttribute('block');
$template = $this->_placeholder->getAttribute('template');
$block = new $blockClass;
$block->setTemplate($template)
->setProductId($this->_placeholder->getAttribute('product_id'));
return $block->toHtml();
}
Run Code Online (Sandbox Code Playgroud)