Frustrated by Magento? Then you’ll love Commerce Bug, the must have debugging extension for anyone using Magento. Whether you’re just starting out or you’re a seasoned pro, Commerce Bug will save you and your team hours everyday. Grab a copy and start working with Magento instead of against it.

Updated for Magento 2! No Frills Magento Layout is the only Magento
front end book you'll ever need. Get your copy
today!

This week’s article is the second in a series discussing Magento 2’s object system. Last time we covered the basics of Magento’s object manager. This week we’re going explain why you’ll rarely use Magento’s object manager, as well as Magento’s implementation of the popular “dependency injection” pattern. (hint — they’re related)

Many popular PHP frameworks implement a dependency injection system — although it would be more accurate to say they implement an automatic dependency injection system. Before we dive into Magento’s system, we’ll want to explain the problem dependency injection sets out to solve.

Understanding Dependency Injection

The easiest way to understand dependency injection is by example. Consider the following PHP method/pseudo-code

This is a simplified example of what a method for fetching a product’s price might look like. On the surface, there’s nothing wrong with this method. It

Instantiates a database handler

Queries for the price

Instantiates a formatter object

Uses the formatter object to return a formatted price

The problem comes later, when someone else wants to reuse this method. This method is now dependent on the specific DBHandler class, and the specific PriceFormatter class. Even if you think code reuse is an untrue industry myth, these two dependencies make this method harder to test in an automated framework. Your test framework is now reliant on making the same database connection as your real application.

The solution to this problems is to not have methods with these sorts of dependencies. Instead, you should inject dependencies into the method.

While we’ve replaced the dependencies in getFormattedPrice — all we’ve really done is shift them up a level to the method that calls getFormattedPrice (prepareDataForDisplay above). So, conceptually dependency injection is simple, but where you inject your dependencies and where these objects are instantiated is left up in the air.

This is the problem that many PHP frameworks try to solve with some sort of automatic dependency injection. By creating a system for automatically injecting these sorts of dependencies the framework removes the question of by who and how a dependency is injected. If that didn’t make sense, don’t worry. After looking at an example of Magento’s dependency injection it should start to make more sense.

All we’ve done in the execute method is instantiate a Pulsestorm\TutorialObjectManager2\Model\Example object and call its sendHelloAgainMessage method to get some output text. If you take a look at this Pulsestorm\TutorialObjectManager2\Model\Example class’s constructor

we see the class instantiates a Pulsestorm\TutorialObjectManager2\Model\Message object and assigned it to the messageObject property. We use the short class name Message since this file lives in the Pulsestorm\TutorialObjectManager2\Model namespace. If you need some help getting started with PHP namespaces, our primer is a good place to go.

Our (contrived) Pulsestorm\TutorialObjectManager2\Model\Example class has a hard coded dependency on the Pulsestorm\TutorialObjectManager2\Model\Message object. Here’s how Magento 2 solves this problem. Open up the Example.php class definition file, and let’s replace the constructor with the following code

What we’ve done here is added a parameter named $message to the constructor, and then assigned that parameter to the messageObject property. In other words, we’ve replaced the hard coded dependency with a parameter. This allows developers to inject the dependency. You’ll also notice we’ve included a type hint with the parameter.

This type hint forces developers to pass in an object that either is a Pulsestorm\TutorialObjectManager2\Model\Message object, or has Pulsestorm\TutorialObjectManager2\Model\Message in its ancestry chain. Again, we’ve used the short class name Message. The following would have been equivalent, but is much more verbose.

That’s the beauty of Magento 2’s automatic dependency injection system. You don’t need to do anything. Just run the command with our new code in place.

$ php bin/magento ps:tutorial-object-manager-2
Hello Again World!

Same results — even though we didn’t do anything to pass in a parameter.

This is automatic dependency injection. Behind the scenes, the object manager will use PHP’s reflection features to look at a class’s __construct type hints/parameters, automatically instantiate the object for us, and then pass it into the constructor as an argument.

That can seem a little weird the first time you encounter it, but if you don’t believe us just add a bit of debugging code to your constructor

Once you’re over the weirdness, you may wonder why this is any better. Isn’t the type hint just the hard coded dependency now?

The difference is the object manager has control over the instantiation of the dependency. As module developers, we get a great deal of power to change how the object manager instantiates an injected dependency. This happens via the module’s etc/di.xml file (the di stands for dependency injection). While Magento 2 doesn’t have “class rewrites” — it does have similar, more powerful features, all configurable via the di.xml file. Over the next few articles we’re going to explore all these options, and you’ll learn how to gain complete control over these dependencies.

So Long Object Manager, We Hardly Knew You

Before we wrap up for today, there’s one last thing to attend to. If you poke around Magento 2’s current documentation for Magento 2’s object system (usually labeled Dependency Injection), you’ll see cryptic comments like the following

The object manager must be present only when composing code, composing code is performed early in the bootstrapping process

Also, if you’ve been following Magento 2 development closely, you’ll know there used to be a static factory method for grabbing an object manager instance, but that method was depreciated and removed.

The object manager class is not meant for day-to-day use in Magento 2. It’s reserved (by convention) for system level developers working on the code that bootstraps Magento. The getObjectManager method we’ve provided in these tutorials was a helper so you could understand what the object manager was.

If you’re following best practices for Magento extension development, you’ll use dependency injection to instantiate almost all your objects. This may seem impossible at first (I was rolling my eyes back in 2013), but as Magento 2 nears completion it’s becoming clearer that this actually is possible.

We’ll be covering the dependency injection features that make this possible in our future articles. However, here’s some high level reassurances that “no objet manager” isn’t as crazy as it sounds.

All objects in Magento are instantiated with the object manager — including dependencies. In other words, the objects you inject with __construct injection can, themselves, have a __construct method with automatically injected dependencies.

Data management objects (what we used to call “ORM Models” in simpler times) can be instantiated via factory objects — these factory objects can be injected via dependency injection.

If it’s dependency injection all the way down, you may wonder what’s on the top of the stack. Remember though, all valid code entry points (a controller action method, an observer object/method, a block object, a Symfony Console command, etc.) are created by configuration. This means Magento knows about them, and when it needs to instantiate them it uses the object manager. This means all these objects have __construct injection

Although it’s not recommended, and may go away in a future release, as of right now there is a way to get an instance of the object manager

Regarding that last item? Take a look at the base Pulsestorm\TutorialObjectManager2\Command\AbstractCommand class

This pattern can take a little getting used to, and may seem like overkill. However, in an enterprise environment consistency is more important than a home run. Constricting day-to-day development along this path and leaving more creative work to the deep level systems developers, an agile focused team can do a better job of hitting its deadlines and calculating its velocity. Boring and corporate as they are, these design patterns are an important part of ensuring Magento 2’s steady, relentless march towards a release.

That’s a lot to digest for a single day, so we’ll leave it there. Next time we’ll explore some of the dependency injection features, including how we managed to inject an object manager using only a PHP interface (ObjectManagerInterface) instead of a class.