i have written code using object manager in Block. i am not sure it is best practice. what are the place use object manager. what are the place we need to avoid Any one suggest please
2 Answers
Use ObjectManager:
- In a Factory or Proxy class, to create object instances.
- In a class
__construct
function, to preserve backward compatibility for an extension you publish. (Don't do this if it's private code for a particular site; you don't need to preserve backwards compatibility.) - In formal tests.
Do not use ObjectManager:
- In a template. (Use DI on that template's block.)
- In a class method. (Use DI in that class's constructor.)
- Anywhere else.
- Out of laziness.
- Because it's raining out.
- Because someone on the internet said you should. Unless your situation is on the list above, they were probably mistaken.
Why? / see also
https://magento.stackexchange.com/a/75204/1905
Magento 2: to use or not to use the ObjectManager directly?
http://devdocs.magento.com/guides/v2.1/extension-dev-guide/depend-inj.html
You should not use the ObjectManager directly!
Exception from the rule are:
- in static magic methods like
__wakeup
,serialize
, etc - in case you should make backward compatibility of constructor
- in global scope, like in fixtures of integration test.
- in class that needs only for creation of object like factory, proxy , etc
Reference: Magento 2: to use or not to use the ObjectManager directly?