Wednesday, July 15, 2020
Home > Beginners of Magento 2 > ObjectManager In Magento 2?

ObjectManager In Magento 2?

Web Development

Large applications, such as the Magento application, use an object manager to avoid boilerplate code when composing objects during instantiation. Lets see, ObjectManager In Magento 2?

In the Magento framework, the implementation of the ObjectManagerInterface performs the duties of an object manager.

The ObjectManager class defines the following three methods:

  • create($type, array $arguments = []): This creates a new object instance
  • get($type): This retrieves a cached object instance
  • configure(array $configuration): This configures the di instance

Responsibilities:

  • Object creation in factories and proxies
  • Implementing the singleton pattern by returning the same shared instance of a class when requested
  • Dependency management by instantiating the preferred class when a constructor requests its interface
  • Automatically instantiating parameters in class constructors

Configuration:

The di.xml file configures the object manager and tells it how to handle dependency injection.

This file specifies the preferred implementation class the objectmanager in magento 2 generates for the interface declared in a class constructor. The file also specifies whether the object manager should create an object for every request or treat the object as a singleton.

Usage rules:

The Magento framework uses the ObjectManager to generate and inject the classes declared in your constructor. Classes should not ask for the ObjectManager itself as a constructor dependency.

You do not call the object manager directly because the framework handles this automatically. Direct use of the create function prevents type validation and type hinting that a factory class provides.

Object creation is also a separate responsibility that should be moved to a dedicated class such as a factory or proxy. In most cases, the framework generates these classes automatically during code compilation.

Note: Magento prohibits the direct use of the ObjectManager in your code because it hides the real dependencies of a class.

Spread the love