Question

I'm trying to make a plugin to extend the \Magento\SalesRule\Model\Validator

Which works like a charm, but the problem is I need to make use of Magento\SalesRule\Model\RuleFactory

I've tried making a __constructor in the plugin class and adding the RuleFactory there through dependency injection as described in het Magento 2 Developer Guide which looked like this:

The entire "Validator" plugin class now looks like this:

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;
    }
}

but this would just return null for $this->ruleFactory at all times.

the di.xml document contains the following:

<?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>

Interestingly enough I found that in the generated Interceptor.php file the constructor is actually made. But it is never called, can anybody tell me why this could be?

Was it helpful?

Solution 3

I decided to go with the less clean solution and just used a static instance of the objectmanager and got the rule factory through that

OTHER TIPS

Late answer but you need to change __constructor to __construct and it will work perfectly well. Don't use static ObjectManager if possible. You should always use DI instead.

Yes, it is supported. Looks like in your sample function keyword is missing, try:

public function __constructor(\Magento\SalesRule\Model\RuleFactory $ruleFactory){
    $this->ruleFactory = $ruleFactory;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top