Magento – Elegant way of constructor dependency injection when extending abstract class

dimagento2PHP

I'm wondering what the best way is to add extra dependencies in the constructor of a class when extending another (abstract) class?

In follow up to this answer regarding dependency injection when extending another class:

https://magento.stackexchange.com/a/74633/24375

Marius mentions this:


The class you are trying to extend has this constructor:

public function __construct(
    \Magento\Framework\View\Element\Template\Context $context,
    \Magento\MediaStorage\Helper\File\Storage\Database $fileStorageHelper,
    array $data = []
) {
    $this->_fileStorageHelper = $fileStorageHelper;
    parent::__construct($context, $data);
}

so you need to make your constructor look like this

public function __construct(
    \Magento\Framework\View\Element\Template\Context $context,
    \Magento\MediaStorage\Helper\File\Storage\Database $fileStorageHelper,
    \Creare\Seo\Helper\Data $creareHelper,
    array $data = []
)
{
    $this->_creareHelper = $creareHelper;
    parent::__construct($context, $fileStorageHelper, $data);
}

Conclusion…
In your child classes you need to specify all the parent class constructor params plus your new params.


To me this solution doesn't seem elegant at all. What if the constructor of a parent class changes? You'd have to rewrite all child classes depending on it.

I'm wondering if there's a way to include all dependecies of the parent class + some other dependencies, without specifying the parent dependencies in the child class?

Thanks!

Best Answer

What if the constructor of a parent class changes?

Yes, its problem and it's why Magento Developers ask do not use inheritance and continue work on frameworks that allow to not do it and did not change constructor in the backward incompatible way (at least in a minor version of modules).

Related Topic