Skip the Object Manager: Better Ways to Handle Dependencies in Magento 2

Skip the Object Manager: Better Ways to Handle Dependencies in Magento 2

Direct use of the Object Manager in Magento 2 creates problems. Magento's official guidelines warn against it because it hurts code quality, slows performance, and breaks standard development patterns. Here's why you should avoid the Object Manager and what to use instead.

The global dropshipping market reached $366.76 billion in 2024 and is projected to hit $470.92 billion in 2025, while global e-commerce sales are expected to reach $9.3 trillion by 2027. Both models offer real opportunities, but they come with different challenges and rewards.

What the Object Manager Does

The Object Manager creates and retrieves objects in Magento 2. It works instantly without declaring dependencies upfront. That sounds convenient, but it causes serious issues in production code.

Tip

To enhance your eCommerce store’s performance with Magento, focus on optimizing site speed by utilizing Emmo themes and extensions. These tools are designed for efficiency, ensuring your website loads quickly and provides a smooth user experience. Start leveraging Emmo's powerful solutions today to boost customer satisfaction and drive sales!

Why Direct Object Manager Use Fails

Breaks Dependency Injection Principles

Magento 2 uses Dependency Injection (DI) to manage how classes connect. DI makes dependencies visible and loosens coupling between components. The Object Manager bypasses this system entirely. Your code becomes tightly linked, harder to test, and resistant to changes.

Reduces Code Clarity

Reading code that uses the Object Manager directly is difficult. Dependencies hide inside methods instead of appearing in constructors. New developers waste time tracing object creation. Debugging becomes a maze of hidden connections.

Slows Execution Speed

The Object Manager performs runtime checks every time it creates objects. This adds processing overhead. Dependency Injection configures objects during compilation, not runtime. Proper DI delivers faster execution and lower resource consumption.

Approach When Dependencies Resolve Performance Impact
Object Manager Runtime High overhead
Dependency Injection Compile-time Optimized

Interferes with Caching

Magento 2 generates code and caches configurations to boost speed. Direct Object Manager use disrupts these systems. You'll see inconsistent behavior across environments. Deployment problems multiply. Following DI patterns keeps code generation and caching working correctly.

Proper Dependency Management Methods

Constructor Injection

Declare what your class needs in its constructor. This makes dependencies explicit and testable.

public function __construct(

ProductRepositoryInterface $productRepository,

StockRegistryInterface $stockRegistry

) {

$this->productRepository = $productRepository;

$this->stockRegistry = $stockRegistry;

}

Service Contracts

Use service contracts to interact with core features. These interfaces create clear boundaries between modules. Your code stays flexible and upgradable.

Factory Classes

Need to create objects on demand? Use factories instead of the Object Manager. Factories follow naming conventions and work with Magento's DI system.

public function __construct(

    ProductInterfaceFactory $productFactory

) {

    $this->productFactory = $productFactory;

}

DI Container Configuration

Configure dependencies in di.xml files. The DI container handles object creation automatically. You can swap implementations without touching class code.

Performance Data

Testing becomes nearly impossible with direct Object Manager usage. You cannot easily mock dependencies when using the Object Manager

When Object Manager Use Is Acceptable

Three specific scenarios allow Object Manager use: inside factory classes where the object type is determined at runtime, within proxy classes implementing lazy loading, and in bootstrap code before the DI system initializes.Even these cases need strong justification.

Real-World Impact

. The compile process rejects code that bypasses DI. The DI system creates shared instances by default and generates factories and proxies to boost performance, while direct Object Manager usage creates unnecessary new instances

Impact Area With Object Manager With Proper DI
Testing Cannot mock dependencies Easy to mock and test
Performance Creates unnecessary instances Optimized shared instances
Marketplace Fails validation Passes checks
Maintainability Hidden dependencies Clear dependencies
Code generation Disrupted Functions properly

Implementation Comparison

Wrong approach:

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();

$product = $objectManager->create('Magento\Catalog\Model\Product');

Correct approach:

public function __construct(

    \Magento\Catalog\Api\ProductRepositoryInterface $productRepository

) {

    $this->productRepository = $productRepository;

}

Conclusion

Direct Object Manager use breaks Magento 2's architecture. It creates technical debt you'll pay later during refactoring. Using Object Manager bypasses Dependency Injection and prevents future features from working correctly Stack Exchange.Constructor injection, factories, and service contracts give you better code that performs faster and tests easier. Follow these patterns from the start instead of fixing problems later.

FAQs

Why should I avoid using the Object Manager directly in Magento 2?

Using the Object Manager directly (e.g. \Magento\Framework\App\ObjectManager::getInstance()) hides dependencies, breaks inversion of control, makes code harder to test, and can produce unexpected behavior during DI compilation. Constructor injection (or factories/proxies) keeps dependencies explicit and the application predictable.

What is the recommended alternative to direct Object Manager usage?

Use constructor dependency injection (type-hinted constructor parameters) where possible. For optional or lazily created objects, use automatically generated Factories, Proxies, or the Object Manager only in very limited circumstances (like bootstrapping or integration tests).

When are Factories and Proxies appropriate?

Use a Factory when you need to create multiple instances at runtime with different constructor arguments. Use a Proxy when you want lazy-loading for a heavy dependency so it is instantiated only when actually used.

How does avoiding the Object Manager improve testing?

Explicit constructor dependencies make it simple to provide test doubles (mocks/stubs) during unit testing. Hidden calls to the Object Manager make mocking difficult or impossible and force fragile integration-style tests instead of fast unit tests.

Does skipping the Object Manager affect performance?

Yes — proper DI lets Magento optimize object instantiation during compilation (setup:di:compile), avoid unnecessary instances, and use proxies for lazy loading, which can reduce memory and improve response time compared to ad-hoc Object Manager calls.

Will using Object Manager break Marketplace or code quality checks?

Magento Marketplace and many code-review tools flag direct Object Manager usage because it indicates poor design. Replacing direct calls with DI, factories, or service contracts improves compatibility with Magento coding standards and marketplace validation.

How does DI improve maintainability in a Magento module?

DI makes dependencies explicit in the constructor, so future maintainers can see what a class relies on. This improves readability, eases refactoring, and reduces hidden side-effects that occur when code reaches into the global Object Manager.

Are there any valid exceptions where Object Manager may be used?

Yes — limited, well-documented exceptions include bootstrap/bootstrap-like scripts, setup scripts, integration tests, and some autogenerated factories. Even then, document the reason and prefer safer alternatives if possible.

How do I refactor existing code that uses the Object Manager?

Identify where the Object Manager is used, determine the actual dependencies, add them to the constructor, and update instantiations. Where dynamic creation is required, replace with a generated Factory or use a Proxy for lazy loading. Run static analysis and tests after each change.

Which Magento features help enforce good DI practices?

Magento’s generated factories/proxies, service contracts (API interfaces), DI configuration (di.xml) and the compilation step (bin/magento setup:di:compile) all work together to encourage explicit DI, detect issues early, and produce optimized, validated code.