Magento 2 – Is Dependency Injection Possible for Plugins?

dependency-injectiondimagento2plugin

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?

Best Answer

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.

Related Topic