in

Magento 2 Constructor Injection Examples to Get You Started

Explore practical Magento 2 constructor injection examples, from adding repositories and services to controllers and blocks. Learn how Magento resolves dependencies, configure and test your module, and avoid common pitfalls such as Object Manager calls, circular dependencies, and compilation errors.

Constructor injection is a clean, dependable way to provide Magento 2 classes with the services and dependencies they need. Once you understand the basics, it becomes much easier to write code that’s organized, testable, and aligned with Magento’s dependency injection system.

In this guide, you’ll explore practical Magento 2 constructor injection examples, from defining dependencies in a class constructor to using them in your code. Whether you’re new to Magento development or looking for a quick refresher, these examples will help you get started with confidence.

Magento 2 Constructor Injection: The Basics

What happens when a class needs a service it didn’t create itself? In Magento, the answer is usually a constructor: it declares what the class needs, while the framework takes care of supplying those objects when the class is instantiated.

Following that process from class definition to object creation makes the examples easier to understand. First, let’s look at how Magento builds the dependency chain.

How Magento resolves constructor dependencies

When Magento needs to create a class, its object manager inspects the constructor and uses each parameter’s type hint to identify the required class or interface. It then resolves those dependencies in turn, creating the objects or retrieving them from the configured object graph.

For example, a class can request a logger without constructing one directly:

namespace VendorModuleModel;
use PsrLogLoggerInterface;
class Report
{
    private LoggerInterface $logger;
    public function construct(LoggerInterface $logger)
    {
        $this->logger = $logger;
    }
    public function run(): void
    {
        $this->logger->info('Report started');
    }
}

Because the constructor asks for an interface, Magento must know which implementation to provide. A preference in a module’s di.xml can map LoggerInterface to a concrete class. This keeps implementation choices outside the class and makes it simpler to substitute dependencies in tests or other environments.

In practice, use constructor injection for stable dependencies a class needs to do its job. Avoid calling the object manager directly; doing so hides requirements and makes the code harder to test.

Type hints describe ordinary dependencies, but Magento also supports generated helper classes and XML configuration. These features are useful when an object must be created later or when its wiring needs to vary by application setup.

Type hints, generated factories, and dependency configuration

A type hint can name a class or an interface, and Magento’s dependency injection configuration determines how that request is fulfilled. For dependencies that need to be created on demand, inject a generated factory rather than creating the object through the object manager.

For a class named ExportJob, Magento can generate an ExportJobFactory for use in a constructor:

public function construct(
    VendorModuleModelExportJobFactory $jobFactory
) {
    $this->jobFactory = $jobFactory;
}

Then call $this->jobFactory->create() when a new job is needed. Factories are especially handy when creation is conditional or when the object should not be instantiated until a particular operation runs.

Use etc/di.xml to define preferences, constructor arguments, or virtual types—named configurations that adapt an existing class without requiring a new subclass. Together, type hints communicate what a class needs, factories handle deferred creation, and DI configuration tells Magento how to connect the pieces.

Magento 2 constructor injection examples for common use cases

With the wiring patterns in place, the next step is seeing how they support everyday Magento tasks. The examples below show how to request data, read configuration, and connect a custom service to storefront code.

A repository is a good fit when a class needs to retrieve or save an entity. Here, the custom class requests Magento’s product repository interface and uses it to load a product by ID.

Injecting a repository into a custom class

Type-hint the repository interface rather than a concrete implementation. Magento can resolve the configured implementation, while the class stays focused on its job.

namespace VendorModuleModel;
use MagentoCatalogApiProductRepositoryInterface;
class ProductLookup
{
    public function construct(
        private ProductRepositoryInterface $productRepository
    ) {
    }
    public function getName(int $productId): string
    {
        return $this->productRepository
            ->getById($productId)
            ->getName();
    }
}

This pattern keeps database access out of the class and makes the repository easy to replace with a mock in a unit test. Handle exceptions such as a missing product at the layer that can decide how the application should respond.

Repositories cover entity access; operational code often also needs diagnostics or store-specific settings. The following example combines those needs without embedding configuration values in the class.

Using a logger or configuration service

Inject LoggerInterface to record useful events, and use ScopeConfigInterface when a value should come from Magento’s configuration system. Passing the store scope when reading a setting helps the value reflect the active store view.

public function construct(
    private PsrLogLoggerInterface $logger,
    private MagentoFrameworkAppConfigScopeConfigInterface $scopeConfig
) {
}
public function isEnabled(): bool
{
    $enabled = $this->scopeConfig->isSetFlag(
        'vendormodule/general/enabled',
        MagentoStoreModelScopeInterface::SCOPESTORE
    );
    $this->logger->debug('Feature enabled: ' . (int) $enabled);
    return $enabled;
}

Keep configuration paths meaningful and define their fields in the module’s admin configuration so merchants can manage them. Avoid logging sensitive values, even at debug level.

Once a service is ready, a controller or block can act as the point where it connects to a request or template. The important detail is to retain the parent class’s required constructor arguments.

Injecting a custom service into a controller or block

For example, a block can receive a custom formatter alongside Magento’s template context. Call the parent constructor so the framework’s block setup remains intact.

public function construct(
    MagentoFrameworkViewElementTemplateContext $context,
    VendorModuleModelProductFormatter $formatter,
    array $data = []
) {
    $this->formatter = $formatter;
    parent::construct($context, $data);
}

Controllers follow the same principle: add the service to the constructor and pass required arguments to the parent. Keep business logic in the service, rather than letting a controller or block grow into a catch-all class.

These examples rely on Magento’s object graph, so finish by checking how the module declares and verifies its wiring. This catches configuration mistakes before they become runtime surprises.

Declaring dependencies in a module and testing the results

If a constructor requests an interface that has no existing mapping, declare a preference in etc/di.xml:

<preference
    for="VendorModuleApiFormatterInterface"
    type="VendorModuleModelFormatter" />

After adding or changing DI configuration, run the relevant compilation and cache commands for the environment. Then test the class by supplying mocked dependencies and checking its behavior; this confirms both that its responsibilities are clear and that it does not depend on direct object-manager calls.

Magento 2 constructor injection examples: Best practices and common pitfalls

The examples above show how dependencies fit together; small design choices determine whether that wiring stays easy to maintain. Keep these practical checks in mind as your module grows, especially when changing constructors or troubleshooting a build.

A long constructor can be a useful warning sign: the class may be taking on too many responsibilities. This subsection covers ways to keep dependencies clear and avoid shortcuts that hide them.

Keep constructors focused and avoid direct Object Manager calls

Each injected dependency should support the class’s core job. If a constructor accumulates unrelated services, consider moving a distinct task into a focused service rather than turning the class into a coordinator for everything.

Calling the Object Manager directly—whether inside a method or the constructor—hides what the class needs and makes tests harder to write. Prefer explicit constructor arguments, and use a generated factory when an object should be created only for a particular operation. A quick review can help:

  • Keep dependencies purposeful: remove services that the class does not use.
  • Use factories for deferred creation: don’t inject the Object Manager as a substitute.
  • Separate responsibilities: move unrelated work into a dedicated service.

Clear constructors also make changes safer for other code that instantiates your class. That matters particularly when a module is already in use.

Adding a dependency can affect subclasses, tests, and integrations that call a constructor directly. Here’s how to make such changes more carefully while accounting for genuinely optional behavior.

Handle optional dependencies and backward compatibility

Before changing a constructor, check its existing call sites and any classes that extend it. Add new required arguments cautiously: changing argument order or adding a required parameter can break code that previously created the class with the old signature.

If a dependency is truly optional, a nullable parameter with a default may preserve compatibility, but avoid silently constructing a fallback through the Object Manager. Define what happens when it is absent, and keep the optional path explicit. When the dependency is essential to the class’s purpose, make it required instead of disguising that requirement.

Even a well-structured constructor can fail to compile if Magento cannot resolve its dependency graph. The next checks help narrow down common wiring and cycle problems.

Diagnose circular dependencies and compilation errors

A circular dependency occurs when services depend on one another, directly or through other classes. For example, if service A needs B while B needs A, Magento cannot build the chain; the useful fix is usually to separate their shared responsibility into another service.

When compilation reports an unresolved argument or dependency loop, inspect the named class, constructor type hints, and relevant di.xml preferences or arguments. Then run compilation in the target environment and review the full error output:

  • Confirm the requested class or interface exists and is autoloadable.
  • Check that interfaces have valid implementations configured.
  • Trace dependencies in both directions to find a cycle.
  • Use a factory or proxy only when deferred creation fits the design—not to conceal a flawed dependency structure.

After correcting the wiring, compile again and test the affected class. A small, explicit dependency graph is easier to troubleshoot and more dependable as your Magento module evolves.

Build clearer, more maintainable Magento 2 modules

These Magento 2 constructor injection examples show how explicit dependencies help keep classes focused, testable, and easier to extend. Whether you’re connecting a repository, configuration service, or custom business logic, Magento’s DI system can handle the wiring when your type hints and configuration are clear.

As you apply these patterns, keep constructors purposeful, use factories when creation needs to be deferred, and check dependency changes for compatibility and cycles. With a well-structured dependency graph, you’ll have a stronger foundation for building and maintaining Magento modules with confidence.

Leave a Reply

Your email address will not be published. Required fields are marked *

      Written by Maeve Rodriguez

      Maeve is a Business Content Writer and Front-End Developer. She's a versatile professional with a talent for captivating writing and eye-catching design.