Dependency injection (DI) is one of the major new features in Magento 2. Dependency injection’s benefits are explained more thoroughly in other pages around the web but hopefully this page helps clarify some usage details.
ObjectManager is responsible for creating objects (known as an Injector in some libraries).
What does the ObjectManager do?
Imagine you have the following 3 classes.
Let’s say that Magento 2 needs a
Controller instance. It uses the
ObjectManager to create an instance of the
ObjectManager is asked to create a
Controller object, the
ObjectManager must figure out what to pass into the
Controller’s constructor parameters. The parameters are the class’s dependencies.
A simple view is the
ObjectManager recursively determines how to create objects for constructor parameters until it can fulfill all the dependencies and then (finally!) creates the
In more detail:
ObjectManagerdetermines that it needs a
HttpRequestobject to pass into the
- Then, the
CookieReaderdoes not have any parameters for its constructor so the
ObjectManagercould just effectively call
- Once the
CookieReader, it can create the
- Finally, the
HttpRequest, so it can create a
This is a basic explanation because there are complex scenarios during object creation but developers usually do not have to worry about how dependencies are fulfilled. Developers specify what they need in their class constructors, and the
ObjectManager will try to figure out how to get the right parameters to pass in.
How is the ObjectManager used in the app?
Starting at the index.php entry point, there are bootstrapping functions that create an ObjectManagerFactory and then initializes an ObjectManager. Once initialized, the
ObjectManager is used to create the real application object which recursively fulfills all of the dependencies. Then the real application object is used to
run() the application.
Should I use the ObjectManager directly?
No, unless you really know what you’re doing.
There are some framework and auto-generated classes that require the
ObjectManager to be passed into their constructors (hey, the ObjectManager knows how to pass itself into a constructor :) ). However, as a best practice, you should not have an
ObjectManager constructor parameter and should not directly instantiate the
If you use the
ObjectManager directly, you are probably using it as a service-locator. Service locators make unit testing more difficult, hide dependencies, and make it difficult to assemble the right dependencies in certain contexts.
Your dependencies should be declared in your constructor, and you should let the framework give you the right objects to construct your type.
Magento 2 supports constructor-based injection as demonstrated above.
Setter/method based injection is not currently used in Magento 2. Setter/method based injection uses set<PropertyName>() methods to inject dependencies versus calling a single constructor.
One advantage of constructor-based injection is a defined method for initialization. Once your constructor is called, you can do whatever you need with all the parameters and not have to worry that only some of the parameters were set. Setter/method based injection sometimes requires a “post-construct” method (either annotated or defined by convention) to do the final initialization after all the setters are called. Constructor-based injection is more verbose however.
No phpDoc required
In Magento 2, phpDoc is not required for dependency injection (but of course, you’re going to document your code when appropriate, right? :) ).
The types for the arguments are gathered from the actual type hint on the constructor parameters. In other words, you need to have the
HttpRequest in the
HttpRequest $httpRequest in the constructor parameter list.
Should I use Interfaces in my parameters?
You should primarily because you should not depend on the actual implementation behind the interface. The Interface is the public API and is much more stable.
Is there any magic to constructor parameters?
If you have default parameter values, these parameters should be last in the parameter list.
Unless a value is specified in an
arguments element in a
ObjectManager will not pass in any value (so your constructor will use the default value).
Also, if you extend a class, you should try to keep the same order of the parameters as your parent class’s constructor. This keeps things sane.
di.xml Configuration File
di.xml files contain the dependency injection configuration. Note that modules can have their own
di.xml such as in the Customer module. Also, modules can have even more specific config for the frontend and adminhtml areas.
Configuration within the same scope will be merged together. More specific scope levels will override the more generic scoped config.
How does the ObjectManager know which real implementation to use for an Interface?
di.xml specifies which implementation to use:
Every constructor that asks for an
EncoderInterface will get a
Magento\Framework\Url\Encoder passed to it.
Shared Object / Singleton Lifecycle
By default, the
ObjectManager creates a single instance of a class and re-uses the same instance across injections. The ObjectManager manages the singleton scope for the object for any code that is instantiated by the ObjectManager (basically everything in Magento 2).
So if you specify a
StoreManager in a Helper class’s constructor and then also specify a
StoreManager in a Controller class, the same
StoreManager will be passed to both constructors.
Note that while this is a managed singleton lifecycle, this is more like a per request lifecycle object in other languages (e.g. in a Java EE application server) due to the nature of the PHP runtime which usually starts one isolated process per request. So the same instance will not be used between 2 different requests.
How to Use Non-Shared Object Lifecycles in Injections
If you need to create objects in your business logic (e.g. you need to create a new model instance), you are generally advised to use a Factory if at all possible.
However, there are cases where you want to declare a type to be a non-shared. In other words, you want a new unique object instance passed into every class that declares a dependency for that type.
In that case, your
di.xml could contain a type element with a shared attribute set to false:
\Magento\Framework\Data\Structure is declared as a parameter in a constructor, the
ObjectManager will pass a new object in every time.
Note that this is similar to a prototype lifecycle in other frameworks/libraries.
What if I want to specify a type for only one constructor?
So if you need to specify the exact type to use in a specific constructor, you can use the following config:
arguments element can contain multiple
argument elements. The
name attribute’s value (“filesystem”) corresponds to the name of the constructor parameter ($filesystem).
xsi:type specifics that you want an object to be passed into the constructor and the argument element value specifies that you want a
\Magento\Framework\Filesystem\Driver\File to be instantiated.
So when a
Magento\Framework\Logger\Handler\System is instantiated, it will be passed in
Magento\Framework\Filesystem\Driver\File to its
$filesystem constructor parameter.
What if my constructor takes a string?
As shown above, you can specify exact argument values in a constructor.
Note that the
xsi:type attribute specifies a string, and the string’s value will be the element’s value. You can see similar configuration for other primitive types.
What if you have a cyclic reference?
Suppose that you have cyclic reference where class
A depends on class
B and class
B depends on class
A. While this should not intentionally occur, it can happen as the dependency graph grows.
You should use a Proxy. It’s as easy as adding some di.xml config:
The Proxy class is automatically created for
\Magento\Framework\Message\Session due to code generation.
Proxies are also useful for lazy-loading types which are expensive to create.
Disclaimer: These are some practical notes about Magento 2, and while I try to be technically accurate, there are edge cases and details that I will gloss over. Note that I did not architect or write any of the relevant code but I do work on the Magento 2 codebase. This is not an official Magento 2 doc. You should find more detailed information at the official Developer Docs.