Magento 2 – How to Define Constructor When Framework Class Gets Overwritten

dependency-injectionmagento2

I've recently created a module for Magento 2 which depends on various Magento framework classes through dependency injection like so:

// Vendor\Module\Helper\Debug
public function __construct(
    \Magento\Framework\App\Helper\Context $context,
    \Magento\Framework\Mail\Message $message,
    \Magento\Framework\Mail\Transport $transport,
    \Vendor\Module\Helper\Config $configHelper
) {
    ...
    parent::__construct($context);
}

This worked well until a third party module was installed that overrides the Message and Transport Framework classes in their di.xml:

<preference for="\Magento\Framework\Mail\Message" type="OtherVendor\Module\Model\Message"/>
<preference for="\Magento\Framework\Mail\Transport" type="OtherVendor\Module\Model\Transport"/>

Now my Module returns the following error

Recoverable Error: Argument 2 passed to Vendor\Module\Helper\Debug::__construct() must be an instance of Magento\Framework\Mail\Message, instance of OtherVendor\Module\Model\Message given

I've already tried deleting the var/generation folder, as well as refreshing and subsequently disabling the Magento cache.

What can I do to change my constructor so that it works either way? So by using either the Magento\Framework\Mail\Message core class or the override class by the third-party module.

Best Answer

You can use the Magento\Framework\Mail\MessageInterface interface in yours __construct method. If someone did rewrite of the class Magento\Framework\Mail\Message, then it shall implement this interface, but isn't obliged to extend a base class.

// Vendor\Module\Helper\Debug
public function __construct(
    \Magento\Framework\App\Helper\Context $context,
    \Magento\Framework\Mail\MessageInterface $message,
    \Magento\Framework\Mail\TransportInterface $transport,
    \Vendor\Module\Helper\Config $configHelper
) {
    ...
    parent::__construct($context);
}

You can read more info here I think third-party module developers make a low-quality rewrite and they don't think about how their module will works with another modules. In my opinion they should extend base class in their rewrite-class.

Related Topic