caching - Magento 将当前产品 ID 传递给模块

标签 caching magento

我有一个自定义模块,可以在我的产品页面上显示数据。我的模块需要获取当前的产品 ID。我尝试使用:

Mage::registry('current_product');

这适用于第一次加载,但是当我刷新时,current_product 不再具有启用全页缓存的数据。

有任何想法吗?

最佳答案

当整个页面缓存处理请求时(这对保持快速处理很有意义),不会调度目录产品操作 Controller 。
因此,永远不会设置注册表变量。
我假设您正在完全缓存的页面上动态生成 block 。
我的建议是尽量避免昂贵的负载,因为这会破坏整页缓存的速度改进。如果可能的话,您真的想缓存该 block ,即使它是每个客户和每个产品的单独缓存条目。

也就是说,这里是如何做到这一点:

在容器中,执行 _getIdentifier()方法:

protected function _getIdentifier()
{
    return $this->_getCookieValue(Enterprise_PageCache_Model_Cookie::COOKIE_CUSTOMER, '');
}

也展开_getCacheId()方法包括方法 _getIdentifier() 的返回值和一个新的占位符属性:product_id
protected function _getCacheId()
{
    return 'HOMEPAGE_PRODUCTS' . md5($this->_placeholder->getAttribute('cache_id') . ',' . $this->_placeholder->getAttribute('product_id')) . '_' . $this->_getIdentifier();
}

接下来,在 block 类中,扩展方法 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;
}

然后启用方法_saveCache()不是 在您的容器类中覆盖它并返回 false .
所以现在,因为容器从 _getCacheId() 返回一个有效的 id , 和 _saveCache()从父类继承, block 可以被缓存,并以有效的方式应用于Enterprise_PageCache_Model_Container_Abstract::applyWithoutApp()中的内容.

您可以通过让容器从 Enterprise_PageCache_Model_Container_Customer 扩展来设置缓存条目的生命周期。而不是 Enterprise_PageCache_Model_Container_Abstract .

如果您仍然需要将 product_id 传递给 block (即使它现在已缓存),您可以在 _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();
}

关于caching - Magento 将当前产品 ID 传递给模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8174021/

相关文章:

css - Woocommerce 产品页面空白?

php - 使用 cURL PHP 与命令行 cURL 清除 Varnish 缓存

php - 获取登录客户 Magento 2.0 的默认账单/送货地址

mysql - 在magento中批量替换产品标题

magento - 应用于special_price 的目录价格规则

magento - 运送到多个地址,但支付一笔费用

php - Magento 布局覆盖!

c - 用于稀疏、惰性、不可变数组的线程安全缓存

java - 当共享 JDBC 缓存存储到位时,将 "numOwners"在 Infinispan 中设置为大于 1 是否有效?

django - 在 Django 中对抗客户端缓存