Magento – Dependency Injection and constructor parameters

best practicemagento2

Lets suppose I have extended a class from magento core and used some extra classes to have a specific functionality. Here is the code (just example).

// core code
public function __construct(
    \Magento\Framework\Model\Context $context,
    \Magento\Framework\Registry $registry,
    array $data = []
)

Now in my module I have added an extra class. Say it's catalog session. Now it looks like this

// module code
public function __construct(
    \Magento\Framework\Model\Context $context,
    \Magento\Framework\Registry $registry,
    \Magento\Catalog\Model\Session $catalogSession, //newly added
    array $data = []
)

Now I know Magento will go through all extended classes until it finds
out a constructor and those parameters will only use to inject
dependencies. So now here it will find the constructor in my module
first so it wont go to parent class at all and i need to ensure that I
will add all parameters from my parent class.

Now my question is what will happen if Magento will change or add or delete any parameters of its core class which we are extending?

Best Answer

Short answer: Your extension will crash.
Long answer:
If they change a constructor signature, the semantic version (major version) of the core module will be increased.
That's why you should declare dependencies in the composer.json file of your module and you should not use wildcards for the major version number of the dependencies.
This way you will get notified when trying to install your module that it will not work.

Related Topic