How object manager work in Magento?
Large applications, such as the Magento application, use an object manager to avoid boilerplate code when composing objects during instantiation.
Magento prohibits the direct use of the ObjectManager
in your code because it hides the real dependencies of a class.
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.
How does it work?
To get the object manager instance use the code:
<?php $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
To add object Manager to constructor:
/ * @var \Magento\Framework\ObjectManagerInterface */ private $objectManager; / * @param \Magento\Framework\ObjectManagerInterface $objectmanager */ public function __construct( \Magento\Framework\ObjectManagerInterface $objectmanager ) { $this->objectManager = $objectmanager; }
Using the ObjectManager you can get a singleton object (method “get”) of PHP class or create a new one (method “create”).
Example
<?php
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
/* Create a new product object */
$product = $objectManager->create(\Magento\Catalog\Model\Product::class);
/* Get a request object singleton
$request = $objectManager->get(\Magento\Framework\App\RequestInterface::class);
Configure Object Manager
The object manager is configured in the di.xml file which tells it how to treat dependency injections. Since the interface is declared in a class constructor, di.xml file also defines the preferred implementation class that the object manager generated for the interface.
At last, di.xml file specifies if the object manager will treat an object as a singleton or create objects for every request.
Exceptions
Attention!!! You should avoid direct use of the ObjectManager in your code as in the example above since it hides real dependencies of the class.
You can use the Object Manager only:
– for the tests of your code
– in factories, proxies classes
– for the backward compatibility changes in the PHP class constructor
– in static magic methods, e.g.: __wakeup, serialize, etc.
Leave A Comment
You must be logged in to post a comment.