Magento 2 magento2, object manager

Object Manager in Magento 2

The initialization of objects in Magento is done via what is called the object manager. The Object Manager itself is an instant of the Magento\Framework\ObjectManager\ObjectManager class that implements the Magento\Framework\ObjectManagerInterface class.

There are three way of initializing the object:

1. create($type, array $arguments = []): This creates a new object instance. The $type argument is a model, block or helper class name or interface name. It is analogous to Mage::getModel().

2. get($type): The get method will check to see if an instance of the object of type $type has already been instantiated and return that. Otherwise, it will instantiate a new object of type $type and return that instead. It is analogous to Mage::getSingleton(). Again, the $type argument is a model, block or helper class name or interface name. If we want to specify that an object we’re injecting should be instantiated as a singleton, then we can specify the shared=” true” attribute in the di.xml. ""

3. configure(array $configuration): The configure method is used to configure the DI instance by passing in an array of configuration parameters. Magento uses class constructor signatures to retrieve information about an object’s constructor dependencies. When a class is constructed, the object manager injects the class’s dependencies, defined in the di.xml file, into the class constructor.

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

Usually, we don’t have to take care of the constructor parameter’s order in Magento.

If we want to use it directly then

$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); //Get Object Manager Instance

Leave a Reply

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