首页 > 解决方案 > 如何在magento 2中添加没有缓存的自定义条件beforeLoad?

问题描述

我正在创建插件以向所有 beforeLoad 产品集合添加自定义条件。但是,我有一个问题。例子:

user_1 使用 cookie inventory=XYZ beforeLoad 函数访问 abc.com/product 将在条件 inventory=XYZ 下运行并返回产品集合,magento 缓存此页面,产品集合跟随 inventory=XYZ。

user_2、user_n 访问 abc.com/product 他们没有库存或库存=GHQ 与 user_1 的库存 cookie 不同。但是 Magento 从缓存中加载产品集合并没有运行到我插件中的 beforeLoad 函数。因此,产品列表结果将与 user_1 的结果相同。

在重新加载页面之前,我创建了在 magento 中调用清除集合缓存的函数。它工作,但它使页面加载非常缓慢。

请帮助我,如何在我的插件中使magento始终调用函数 beforeLoad 而无需重新加载页面?或其他解决方案来调用以自定义条件重新加载产品集合。

我的代码如下:

public function beforeLoad(\Magento\Catalog\Model\ResourceModel\Product\Collection $subject, $printQuery = false, $logQuery = false)
    {
        $areaCode = $this->_state->getAreaCode();
        $inventory_source = $this->_request->getParam("inventory");
        /*if(isset($_COOKIE["inventory"])){
                $inventory_source = $_COOKIE["inventory"];
        }*/
        if($areaCode == 'frontend' && $inventory_source != ""){
            $joinCondition[] = "e.sku = isi.sku";
            $joinCondition[] = "isi.source_code = '".$inventory_source."'";
            $joinCondition = implode(' AND ', $joinCondition);
            if (!$subject->isLoaded()) {
                $subject->getSelect()
                    ->join(
                        [ 'isi' => $subject->getTable('inventory_source_item') ],
                        $joinCondition,
                        []
                    );
            }
        }
        return [$printQuery, $logQuery];
    }

非常感谢,BienHV

标签: phpmagentomagento2

解决方案


由于您提到了“不同的库存 cookie”,听起来您想根据 cookie 值呈现不同的页面内容。

如果我的理解是正确的,那么您将从使用可变字符串配置页面变体中受益。

Magento 2 参考:https ://devdocs.magento.com/guides/v2.4/extension-dev-guide/cache/page-caching/public-content.html#configure-page-variations


推荐阅读