I am new in Magento 2.
I wanted to know, what is dependency injection in magento 2.
What the concept is about, and how to use it in our framework ?
I have referred this documentation
But still haven't got the concept correctly.
Magento Stack Exchange is a question and answer site for users of the Magento e-Commerce platform. It only takes a minute to sign up.Sign up to join this community
Inside a project, classes interact with each other.
So we can say, a class depends on other classes.
And there are 2 ways the connection can be made.
Magento 1 takes the first approach. Here is a random example. In this example, the category model depends on the url rewrites instance. So it instantiates it.
Magento 2 takes the second approach.
When building a class, all the dependencies are specified in the constructor.
When used, the class is instantiated via a factory method that reads the signature of the class constructor, to check what dependencies are required.
Magento 2 also has a dependency injection container (DIC) which is basically a big array with the classes that get instantiated.
When trying to instantiate a class, it checks if it's dependencies are already present in the DIC.
If they are, they are provided to the constructor, if not, the dependency class is instantiated in the same way as the current class you are trying to instantiate.
This is it in a nutshell. In practice is a bit more complicated because configuration files are involved also (
di.xml), some dependencies might be interfaces which cannot be instantiated, but this factory method supplies a class that implements that interface when your class gets instantiated, based on the contents of the same
Also some dependencies are not objects. They can be arrays, string, ... They are supplied to the class via the same
If you want to dig and see how it actually happens, you can start from this class
But it's not an easy thing to follow. You need some patience.