Magento 2 Object Manager is a PHP class responsible for creating and retrieving objects in Magento 2. It also manages to create factories and proxies.
To get the object manager instance use the code:
<?php $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
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);
Attention!!! You should avoid direct use of the ObjectManager as in the previous example in your code as it hiders 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.