-1

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

3

Use ObjectManager:

  1. In a Factory or Proxy class, to create object instances.
  2. 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.)
  3. In formal tests.

Do not use ObjectManager:

  1. In a template. (Use DI on that template's block.)
  2. In a class method. (Use DI in that class's constructor.)
  3. Anywhere else.
  4. Out of laziness.
  5. Because it's raining out.
  6. 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

|improve this answer|||||
2

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?

|improve this answer|||||

Not the answer you're looking for? Browse other questions tagged or ask your own question.