Skip to content
Tutorials Center
My learning

Topics

Lesson 7 of 42 ยท Dependency Injection

The Object Manager and Constructor Injection

Learn how Magento 2 builds objects, why you should never call the ObjectManager directly, and how constructor injection and autowiring work, with a runnable stand-in.

Almost every Magento class you write will not create its own helpers. A controller does not call new Logger(), and a block does not open its own database connection. Instead the class asks for what it needs in its constructor, and Magento hands those objects over when it builds the class. This is dependency injection, and it is the backbone of the framework: plugins, preferences, virtual types and proxies (the next lessons) are all features built on top of it.

The part of Magento that builds objects is the Object Manager. You will meet it in a few places in core code, and you will see it in old tutorials and legacy modules. Your own code should almost never touch it. This lesson explains what it does, why direct use is discouraged, and how constructor injection works. If the general idea is new to you, read Dependency Injection and Containers first, because Magento's container follows the same principles.

Magento cannot run on this site. The real Magento PHP and XML below is read-only. The runnable examples are small plain-PHP stand-ins that imitate the idea (constructor autowiring by type hint). They are not Magento code, and each lesson says which is which.

What the Object Manager does

The Object Manager implements Magento\Framework\ObjectManagerInterface. It has two methods you will see most often:

  • get($type) returns a shared instance: the first call builds the object, later calls return the same one (like a singleton, but managed by the container, not by the class).
  • create($type, array $arguments = []) builds a new instance every time.

Behind both, the Object Manager reads the constructor of the requested class with reflection, looks at each parameter's type hint, builds those objects first (recursively), and passes them in. Scalar parameters such as strings and ints cannot be guessed from a type, so they come from di.xml configuration or from the $arguments you pass to create(). The rules for what gets built come from the merged di.xml files of all enabled modules, which later lessons cover in detail.

flowchart TD
    A["Your code asks for Magento\Catalog\Block\Hello"] --> B["Object Manager reads constructor"]
    B --> C["Needs LoggerInterface"]
    B --> D["Needs ScopeConfigInterface"]
    C --> E["di.xml preference picks a class"]
    D --> F["di.xml preference picks a class"]
    E --> G["Build dependencies first"]
    F --> G
    G --> H["new Hello(logger, config)"]

The Object Manager walks the constructor type hints, builds each dependency, then builds your class.

Constructor injection in a real module

This is what a typical Magento class looks like. It is read-only here because it needs the framework:

PHP
<?php
declare(strict_types=1);

namespace Acme\Greeting\Model;

use Magento\Framework\App\Config\ScopeConfigInterface;
use Psr\Log\LoggerInterface;

class Greeter
{
    public function __construct(
        private readonly ScopeConfigInterface $scopeConfig,
        private readonly LoggerInterface $logger
    ) {
    }

    public function greet(string $name): string
    {
        $prefix = (string) $this->scopeConfig->getValue('acme_greeting/general/prefix');
        $this->logger->info('Greeting ' . $name);

        return trim($prefix . ' ' . $name);
    }
}

Nothing in the class says which logger or which config reader to use. It declares interfaces, and Magento decides the concrete classes from configuration. That is what lets a store owner, a module or a test replace an implementation without editing Greeter.

You never register Greeter anywhere. Any class that is requested by type name can be built automatically, as long as every constructor parameter is either an injectable type or has a configured value. This is autowiring by type hint.

If a class extends a core class, it must pass the parent's dependencies along, because the parent needs them too:

PHP
<?php
declare(strict_types=1);

namespace Acme\Greeting\Block;

use Magento\Framework\View\Element\Template;
use Magento\Framework\View\Element\Template\Context;

class Hello extends Template
{
    public function __construct(
        Context $context,
        private readonly \Acme\Greeting\Model\Greeter $greeter,
        array $data = []
    ) {
        parent::__construct($context, $data);
    }
}

The Context object is a core example of a class that exists only to bundle many dependencies so that subclasses need fewer constructor parameters. The array $data = [] parameter is a Magento convention for configuration passed from layout XML or di.xml; because it has a default, the Object Manager can leave it empty.

Why you should not call the Object Manager yourself

It is technically possible to write this anywhere:

PHP
$greeter = \Magento\Framework\App\ObjectManager::getInstance()->get(\Acme\Greeting\Model\Greeter::class);

Do not do it in modules. The reasons are practical:

  • Hidden dependencies. The class signature no longer shows what the class needs. This is the service locator problem described in the PHP lesson on DI.
  • Harder tests. A unit test cannot hand in a fake, because the class reaches for a global instead of using its constructor.
  • Fights the framework. Plugins, preferences and compilation work best when dependencies are declared in constructors, so Magento can see them ahead of time.
  • Code-quality tools flag it. Magento's own coding-standard checks warn about direct Object Manager use.

Core code does use the Object Manager inside a few low-level places (bootstrapping, factories, and some legacy classes kept for backward compatibility). That is the framework's job, not a pattern to copy.

Generated code and compile mode

Constructor reflection is not free. In developer mode Magento works out definitions while it runs, and creates helper classes on demand. In production mode you run bin/magento setup:di:compile during deployment. It scans all modules, precomputes the constructor definitions and plugin lists, and writes generated classes into the generated/ directory, so a live request does no reflection work. The details of the generated classes (factories, proxies, interceptors) are in Factories, Proxies and Generated Code. The directory layout itself was introduced in Architecture and Directory Layout.

A stand-in Object Manager

The stand-in below does what the real one does at its core: read the constructor with ReflectionClass, build each class-typed parameter recursively, apply configured scalars, and keep shared instances for get().

PHP A mini Object Manager with autowiring

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Greeter was never registered. The stand-in found Config and Logger from the type hints, and Logger (an interface) needed one prefer() call, which stands for a di.xml preference (next lesson).

What happens when a parameter cannot be resolved? Real Magento throws an exception too. Here is the same failure in the stand-in, which is how you will meet it in practice: a scalar with no default and no configuration.

PHP An unresolvable constructor argument

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

In Magento the fix is a <type name="..."><arguments> entry in di.xml; the lesson on virtual types and constructor arguments shows the syntax.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the difference between ObjectManager get() and create()?

    get() keeps one shared instance per type, create() builds a fresh object (and accepts runtime arguments).
  2. 2. Why is calling ObjectManager::getInstance() inside a module class discouraged?

    A class that pulls dependencies from a global hides what it needs and cannot easily receive test doubles. It still exists in core for framework internals.
  3. 3. How does Magento know which objects to pass to a constructor?

    Type hints identify the dependencies, preferences choose concrete classes for interfaces, and di.xml arguments supply scalars.
  4. 4. What does bin/magento setup:di:compile do for production?

    Compilation moves dependency analysis to deploy time. Minifying assets and schema changes are other commands.

Summary

  • The Object Manager builds objects by reading constructor type hints; get() shares instances, create() builds new ones.
  • Declare dependencies in the constructor, preferably as interfaces; never call ObjectManager::getInstance() in your own modules.
  • Scalars and runtime values come from di.xml arguments or the create() arguments.
  • Subclasses of core classes must pass the parent's constructor dependencies along.
  • setup:di:compile precomputes definitions and generated code for production.
  • The runnable stand-in imitates autowiring; the real Object Manager adds caching, plugins and many more rules.

Next: Preferences and Interfaces in di.xml