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.
How does it work?
To get the object manager instance (e.g. get magento 2 object manager in phtml) 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.
Object Manager in Action
Here you can find a few examples of using $objectManager for different Magento development tasks:
✔ Magento 2 Get Current Store ID, Code, Name, Website ID, URL
✔ How to Create Simple Product Programmatically in Magento 2?
✔ Programmatically assign attribute to all attribute sets in Magento 2