2

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!

1 Answer 1

1

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).

4
  • Thanks. One question: "it's why Magento Developers ask do not use inheritance", so how do we prevent unneeded code duplication when we shouldn't use inheritance? Which design pattern to use? Commented Nov 17, 2016 at 20:50
  • We extract logic in separate class and use composition
    – KAndy
    Commented Nov 18, 2016 at 9:05
  • I was wondering the same about inheritance. Could you elaborate what you mean? Maybe with a real life example?
    – omsta
    Commented Mar 12, 2019 at 10:12
  • Magento's documentation does a good job at explaining the differences of inheritance and composition and why they chose this direction - devdocs.magento.com/guides/v2.3/ext-best-practices/…
    – rain2o
    Commented Apr 11, 2019 at 12:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.