What is difference on both Object manager?
-
23-01-2021 - |
Question
What is difference on both and how will i understand to where should i use any one of these ?
\Magento\Framework\ObjectManagerInterface
\Magento\Framework\App\ObjectManager::getInstance()
if i use
\Magento\Framework\App\ObjectManager
In constructor then.
Solution
There is no difference between use of ObjectManagerInterface
and ObjectManager
class. As When you use ObjectManagerInterface
it will give instance of ObjectManager
class.
\Magento\Framework\App\ObjectManager
\Magento\Framework\ObjectManagerInterface
But You should never use ObjectManager
directly in the code. It will Automatically come in use when we specify Factory Classes in constructor.
If due to some application constraints, you need to use ObjectManager then use ObjectManagerInterface
in constructor.
OTHER TIPS
First you must know what are interfaces?
Interfaces are 100% abstract classes – they have methods but the methods have no ‘guts’
Interfaces cannot be instantiated – they are a construct in OOP that allows you to inject ‘qualities’ into classes .. like abstract classes.
- Where an abstract class can have both empty and working/concrete methods, interface methods must all be shells – that is to say, it must be left to the class (using the interface) to flesh out the methods.
Below reference will guide when to use interface and when to direct class.
Using in constructor is a better choice then the other way, as you are injecting it into the class.
The other way is also used but it is not good. I use the other way only when i am overriding a class which has many injected classes, so if i inject my new class in the child class then i have to override the contructor of parent class. which means i have to inject all classes in parent also in classed and call the parent class. So to avoid this i use object mangener.