Introduction to Magento 2 Object Manager
Vinh Jacker | 11-11-2024
Object-oriented programming started in PHP 5 but has some restrictions compared to other languages. In Magento 1, the Mage class was used to handle most objects. In Magento 2, Object Manager replaces Mage, fixing issues by connecting three patterns: managing objects, injecting dependencies, and using plugins. Object Manager is a PHP class that helps make and find objects in Magento 2. It is also in charge of making types of objects called factories and proxies.
Object Manager Mechanism
To obtain the Magento 2 Object Manager instance ( for example, getting the object manager in phtml), you can use the following code:
<?php
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
To get the object Manager in the constructor:
/
* @var \Magento\Framework\ObjectManagerInterface
*/
private $objectManager;
/
* @param \Magento\Framework\ObjectManagerInterface $objectmanager
*/
public function __construct(
\Magento\Framework\ObjectManagerInterface $objectmanager
) {
$this->objectManager = $objectmanager;
}
With the Object Manager, you can either obtain a single instance of a PHP class (using the “get” method) or generate a new one (using the “create” method).
For 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);
Object Manager Configuration
The di.xml
file sets up the object manager and instructs it on managing dependency injection.
It shows the desired class implementation that the object manager should use for interfaces declared in constructors.
Additionally, it determines whether the object manager should generate a new object for each request or if it should treat the object as a singleton.
Exceptions in Object Manager
It’s essential to refrain from directly employing the ObjectManager in your code, as shown in the previous example, as it hides the actual dependencies of the class.
You can use the Object Manager in the following scenarios:
- When testing your code.
- Depending on classes used to create objects like factories or proxies classes.
- To maintain backward compatibility adjustments in the PHP class constructor.
- In static magic methods, such as __wakeup(), __sleep(), etc.
Object Manager in Use
Examples showing the use of Object Manager for various Magento development tasks: