Categories
Magento

How to use ObjectManager directly at Magento 2

The short answer is you should not use the ObjectManager directly at all. It is a bad practice, and lets talk why.

You should never use \Magento\Framework\App\ObjectManager::getInstance(). Yes, it is simpler to write code, and the code will work, but the performance will be very bad. Also, it completely breaks the dependency injection. You should think more about dependencies, encapsulation, and modularization. Using the object manager is already a violation against the Law of Demeter. And yes, without using ObjectManager there will be more code, but it will be more clear and maintainable.

At Magento 1 we had used the ObjectManager directly very often, and Magento 2 has some legacy from it even now. That’s why some could ask, why even Magento uses ObjectManager directly sometimes. Magento uses it mainly because of its long history and in the future I hope it will be cleared from this. And I see Magento Core developers are moving forward in that direction.

Of course, there are some exceptions, where you can still use ObjectManager directly:

  • when you should make backward compatibility of the constructor
  • in class that needs only for creation of object like factory, proxy, etc
  • in static magic methods like __wakeup, serialize, etc
  • in global scope, like in fixtures of integration test

Leave a Reply

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