我正在尝试制作一个插件来扩展 \Magento\SalesRule\Model\Validator

这就像一个魅力,但问题是我需要利用 Magento\SalesRule\Model uleFactory

我尝试在插件类中创建一个 __constructor 并通过依赖项注入添加 RuleFactory,如 Het Magento 2 开发人员指南中所述,如下所示:

整个“Validator”插件类现在看起来像这样:

class Validator{
    /**
     * @var \Magento\SalesRule\Model\RuleFactory
     */
    private $ruleFactory;

    /**
    * @param \Magento\SalesRule\Model\RuleFactory $ruleFactory
     */
    public function __constructor(\Magento\SalesRule\Model\RuleFactory $ruleFactory){
        $this->ruleFactory = $ruleFactory;
        error_log('validator constructed');
    }

    public function aroundInit(\Magento\SalesRule\Model\Validator $subject, $procede, $websiteId, $customerGroupId, $couponCode){
        //custom before code
        $return = $proceed($websiteId, $customerGroupId, $couponCode);
        //custom after code
        return $return;
    }
}

但这只会为 $this->ruleFactory 始终返回 null。

di.xml 文档包含以下内容:

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <type name="\Magento\SalesRule\Model\Validator">
        <plugin name="ValidatorPlugin" type="\MAS\CouponAttempt\Model\SalesRule\Validator" sortOrder="1" disabled="false"/>
    </type>
    <type name="\MAS\CouponAttempt\Model\SalesRule\Validator">
        <arguments>
            <argument name="ruleFactoryInjection" xsi:type="object">Magento\SalesRule\Model\RuleFactory</argument>
        </arguments>
    </type>
</config>

有趣的是,我发现在生成的 Interceptor.php 文件中实际上创建了构造函数。但它从未被调用过,有人能告诉我为什么会这样吗?

有帮助吗?

解决方案 3

我决定使用更清晰的解决方案,并刚刚使用ObjectManager的静态实例,并通过该静态实例进行了规则工厂

其他提示

迟到的答案,但你需要改变 __constructor__construct 它会工作得很好。如果可能,不要使用静态 ObjectManager。您应该始终使用 DI。

是的,支持。看起来像在你的样本中 function 缺少关键字,请尝试:

public function __constructor(\Magento\SalesRule\Model\RuleFactory $ruleFactory){
    $this->ruleFactory = $ruleFactory;
}
许可以下: CC-BY-SA归因
scroll top