Introduction to Object Manager in Magento 2

object manager in magento 2

Introduction

Magento 2 is a powerful eCommerce platform. It is built using modern PHP principles, and one of its key parts is the Object Manager. 

When you start building custom modules or working with core files in Magento 2, understanding the Object Manager becomes very important. It helps the platform create, manage and deliver objects automatically when they are required. If used wisely, it can make your code clean and well-structured.

Let’s now understand how Magento 2 Object Manager works and where it fits into its architecture.

What exactly is Magento 2 Object Manager?

Magento 2 Object Manager is a built-in class. Its job is to create and fetch PHP objects as and when needed by the system. Thus, Magento uses Object Manager internally to resolve dependencies and create objects based on DI configurations.

You do not need to manually write code to create every class object. Object Manager automatically checks what the object needs, then prepares and delivers it. It supports Dependency Injection (DI) and plays a major role in Magento’s modular structure.

This class is located at \Magento\Framework\ObjectManagerInterface and implemented by \Magento\Framework\ObjectManager\ObjectManager. 

\Magento\Framework\App\ObjectManager is a wrapper used to access the Object Manager in legacy or bootstrap code.

How Does the Object Manager in Magento 2 Work?

Object Manager works with two main functions: get() and create(). Each one has a specific purpose. These methods help retrieve singleton and new instances, but Object Manager also supports other advanced service resolution techniques behind the scenes.

In Magento, many classes are reused again and again. For example, the same class may be required by multiple modules or functions. Now, should Magento create a fresh object each time? No. That’s why these two methods exist. They help manage memory, performance and object lifecycles in the system.

Here’s what each does:

  1. get() Method

This method returns a singleton object. That means Magento will give you the same object instance each time you call get() for that class.

Use this when you want to reuse a shared object and not create a new one every time.

Example:

$request = $objectManager->get(\Magento\Framework\App\RequestInterface::class);

   2. create() Method

This method gives you a new object instance each time you call it.

Use this when you want a fresh object that is independent and not shared with other code.

Example:

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

   3. Why Use These Methods Carefully?

Using create() everywhere can affect performance and memory. Using get() everywhere can cause bugs if the object stores changing data. So, choosing between them depends on the use case.

   4. Object Lifecycle Handling

Object reuse is determined by the scope and lifetime of the dependency, which may be influenced by DI configuration, but get() always returns a shared instance, and create() always returns a new one.

   5. Flexibility With Factories and Proxies

Magento adds extra features using the Object Manager, like factories (for creating multiple instances) and proxies (for lazy loading). These features help build flexible and powerful modules.

Object Manager vs Dependency Injection

Magento 2 is designed around Dependency Injection. So then why do we still need Object Manager?

Well, Object Manager is the engine that powers Dependency Injection. Magento reads your class constructor, checks which classes it needs, and then uses the Object Manager to deliver them. So, Object Manager works in the background, while DI helps you code in a better way.

Let’s now explore how Object Manager is configured and how it knows what to return.

How Object Manager is Configured in Magento 2

Magento doesn’t just randomly decide how to create or return an object. It follows proper rules and settings written in a file called di.xml. This file tells Magento what kind of object to prepare and how it should behave.

The Object Manager acts like a delivery system. But who gives the delivery list? That list comes from the Dependency Injection configuration written in di.xml.

This file is mostly found in the etc folder of a module. Here’s what it does:

  1. Declares Class Preferences

It defines which actual class Magento should use when an interface is requested. This keeps the code flexible because you can change classes without changing all your PHP files.

<preference for=”Vendor\Module\Api\MyInterface” type=”Vendor\Module\Model\MyModel” />

  2. Defines Singletons and New Instances

di.xml also mentions if a class should be reused (singleton) or recreated every time.

  3. Supports Plugins and Interceptors

Magento allows you to extend or modify the behaviour of existing classes using plugins. The object manager uses these settings to inject the right behaviour when the object is created.

  4. Works Across Modules

Every Magento module can have its own di.xml, and Magento combines them all intelligently. So you can customize the behaviour of classes without touching the core code.

  5. Manages Factories, Proxies, and Virtual Types

You can define special object types in di.xml, which helps with performance, lazy loading, or reducing tight connections between classes.

When Should You Use an Object Manager in Magento 2?

Magento 2’s official guidelines clearly say that direct use of the Object Manager in your code is not recommended. But still, there are a few situations where using Object Manager is allowed.

Moreover, Magento wants you to write clean code using Dependency Injection. But in some rare situations, DI cannot be used, and that’s when Object Manager becomes necessary.

Here are those accepted situations:

   1. In Static Magic Methods

Methods like __sleep() or __wakeup() cannot accept constructor arguments. So if you need any object inside them, you have to use the Magento 2 Object Manager, but this should be extremely rare and carefully justified.

   2. For Backward Compatibility

If you are working with older code and don’t want to change the constructor of the class, Object Manager can help get objects dynamically without breaking the existing setup.

   3. Inside Factories and Proxies

Sometimes classes are auto-generated (like factories or proxies), and you cannot inject dependencies directly. These are special use cases where the Object Manager is used internally.

   4. For Testing Purposes

While writing unit tests or integration tests, developers may use Object Manager to create objects on the fly.

   5. In Non-Injectable Scenarios

In some custom helper functions or scripts where DI is not available, the Object Manager in Magento 2 can be used as the last option.

   6. For Tools or Debugging Scripts

CLI commands or short scripts where object creation is needed quickly can sometimes use Object Manager.

Best Practices for Using Magento 2 Object Manager

Here are a few practical and developer-focused tips:

   1. Always Prefer Constructor Injection

If your class depends on other classes, define them in the constructor. Magento will automatically inject them using the Object Manager in the background.

   2. Avoid $objectManager = \Magento\Framework\App\ObjectManager::getInstance()

This approach hides dependencies. Your class will become harder to test and debug. Avoid using this line unless it’s absolutely necessary.

   3. Do Not Use Blocks, Helpers, or Models Directly

Instead, use Dependency Injection in these classes. Magento will handle object creation based on the constructor. This applies to helpers and models as well. All non-factory services should be injected via the constructor for better testability and maintainability.

   4. Keep Object Creation Outside Business Logic

Don’t create new objects inside loops or logic-heavy functions using Object Manager. It affects performance and readability.

   5. Use Factories Where Needed

If you need multiple instances of the same class, create a factory using DI. Magento will generate the factory class automatically.

How to Use Object Manager in Magento 2 Development

Here are some common usage examples of Magento 2 Object Manager:

   1. Getting the Object Manager in the phtml File

Sometimes you need to call a class in a view file. Though it’s not the best practice, it still happens in small projects or quick customisations.

<?php

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

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

This will create a new product model object, which you can use to load data.

   2. Getting Request Object

If you want to access the current request parameters:

$request = $objectManager->get(\Magento\Framework\App\RequestInterface::class);

This gives you access to request methods like getParam() or getPostValue().

   3. Getting Shopping Cart Details

You can get cart items, total, and customer info using Object Manager.

$cart = $objectManager->get(\Magento\Checkout\Model\Cart::class);

$items = $cart->getQuote()->getAllVisibleItems();

You can then loop through $items to fetch quantity, product name, or price.

   4. Creating Helper or Custom Classes Programmatically

Sometimes you create your own helper class and want to load it directly for a script or controller:

$helper = $objectManager->get(\Vendor\Module\Helper\Data::class);

This helps in small automation or cron job scripts.

   5. Loading Customer Data

If you want to fetch customer data outside the controller or block:

$customer = $objectManager->create(\Magento\Customer\Model\Customer::class)->load($customerId);

This loads a customer object based on ID.

   6. Programmatically Create Product

You can even use Object Manager to create a product programmatically:

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

$product->setName(‘Sample Product’);

$product->setSku(‘sample-sku’);

// set other values and save

$product->save();

This approach is useful in custom data import scripts or automation tools. 

You can also use repositories (\Magento\Catalog\Api\ProductRepositoryInterface) or factories (\Magento\Catalog\Model\ProductFactory) instead for product operations.

Conclusion

Magento 2 Object Manager is a core part of the framework. It helps the system manage how objects are created, injected, and used across the application. While it gives a lot of power, it must be used with responsibility.

It controls object creation, dependency injection, plugins, and even system-level logic. All in all, it sits at the heart of the architecture.

Try building your own module and observe how Magento injects classes. This will make your understanding deeper.

Avoid shortcuts, use Object Manager only where it fits, and build habits that make your work future-proof.

 

FAQs

What is the Object Manager in Magento 2?

Object Manager in Magento 2 is a core PHP class responsible for creating and retrieving object instances. It is used behind the scenes to handle dependency injection and object lifecycle in the Magento framework.

What is the function of the Magento 2 Object Manager?

The main function of the Object Manager is to manage object creation and injection. 

Object Manager returns a shared instance using get() or creates a new instance using create(), regardless of DI configuration. However, DI settings (like virtual types, plugins, etc.) may influence the behaviour of the instantiated object.

Should I use Object Manager directly in Magento 2 development?

Magento recommends avoiding the direct use of Object Manager in your code. Instead, use constructor-based dependency injection to keep your code clean, testable, and upgrade-safe.

magento 2 object manager

object manager in magento 2

About the Author
Posted by Bansi Shah

Through my SEO-focused writing, I wish to make complex topics easy to understand, informative, and effective. Also, I aim to make a difference and spark thoughtful conversation with a creative and technical approach. I have rich experience in various content types for technology, fintech, education, and more. I seek to inspire readers to explore and understand these dynamic fields.

Drive Growth and Success with Our VPS Server Starting at just ₹ 599/Mo