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

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

  • 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? – Milan Simek Nov 17 '16 at 20:50
  • We extract logic in separate class and use composition – KAndy Nov 18 '16 at 9:05
  • I was wondering the same about inheritance. Could you elaborate what you mean? Maybe with a real life example? – omsta Mar 12 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 Apr 11 at 12:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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