Dependency injection with Object Manager in Magento
Free Preview
Learn dependency injection in Magento Object Manager for flexible PHP class creation and powerful extensibility.
Lesson Content
Before continuing, let’s take a step back for a moment. If you aren’t familiar with dependency injection, or DI, here’s a brief summary.
Dependency injection is a more structured way to create objects. Rather than using the new keyword to create objects, the classes which you’d like to create objects from are passed into your class’s constructor. In PHP, this is the __construct function.

When code in this class is executed, the classes we passed into the constructor are then all passed into a single class that is responsible for handling the creation of objects from these classes. This class is known as the “dependency injection container”.
The dependency injection container class in Magento is known as Object Manager. While the Object Manager should never be called directly in our code, this class is responsible for creating & managing all of the dependencies in Magento. When we pass it a class, it does it’s magic and then returns the appropriate instance of that class as an object. This object is then assigned to the related class property.
Having a single place for all of these objects to be created provides quite a few benefits:
- First, it decouples our code so that we aren’t directly creating objects in random places throughout our code. Since all objects are created in one place, we let that class manage the dependencies for us. This makes testing our code easier & allows us to write less complex code.
- Since a class now controls how objects are created, extra functionality can be injected into each newly created object. This can supercharge these objects with additional functions & abilities that we can’t easily get with the
newkeyword. - Dependencies can be swapped out with instances of other objects at the time these objects are created. This is where the magic of Magento’s crazy-powerful extensibility shines, and also where most of its complexity comes from. But there is an unbelievable amount of control that we gain from having the capability to do this.
Join the discussion!
Comments
Want to comment on this lesson?
Enroll in this course to leave comments.