Home >Quick overview of Object Manager in Magento 2

Quick overview of Object Manager in Magento 2

Compared to other programming languages, object-oriented programming has been around since PHP 5 and contains a lot of limitations.

In Magento 1, almost all objects are implemented and called through the Mage class. In Magento 2, Object Manager is used to replace the Mage class. This helps to resolve some of the problems when you instantiate parameters by creating tight relationships between 3 patterns: object management, dependency injection, and plugins.

Mechanism

The Object Manager is mainly responsible for the instantiation and configuration of an Object through two main methods: GET, CREATE.

  • The GET method returns a singleton object (an instance of the class used to share among components when running Magento).
vendor/magento/framework/ObjectManager/ObjectManager.php::get()
magento-2-object-manager

  • The CREATE method returns a completely new object (a new instance of the class).
vendor/magento/framework/ObjectManager/ObjectManager.php::create()
magento-2-object-manager

Therefore, if you call the GET method from 2 places, the same result will be generated. Otherwise, you will get a new object if you use the CREATE method.

Object Manager configuration

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

This file specifies the preferred implementation class that the object manager creates for the interface declared in a constructor class. The file also specifies whether the object manager will create an object for every request or the object is a singleton.

Object Manager’s goal

  • Use the object manager to instantiate and insert the declaration class in the constructor.

The object manager can be instantiated in a php class, it can be a model, hepler, or block. Unless the class we are working on has received an instance of the object manager, we can obtain it by passing ObjectManagerInterface to the constructor class like below:

public function __construct(
 \Magento\Framework\ObjectManagerInterface $objectManager
) {
   $this->_objectManager = $objectManager;
}

  • Implement the singleton pattern (learn more at https://en.wikipedia.org/wiki/Singleton_pattern)
  • Manage dependencies
  • Automatically initialize parameters

According to Magento’s core group, you should not use Object Manager in modules because it makes the class lose dependency injection.

You can use Object Manager in the following exceptions:

  • Use Object manager in static magic methods such as __wakeup (), __sleep (), …
  • Use Object manager to maintain backward compatibility for a constructor
  • The Object manager can be a dependency in classes that are used to create objects like factories or proxies.
< Previous Post
Next Post >
Tran Van Toan
+ posts