0

I am little bit confuse, how to use object manager. I have checked this answer but not getting satisfied answer.

Always we are recommending that never use objectManager like \Magento\Framework\App\ObjectManager::getInstance().

Instead of use this :

public function __construct(
   ...
   \Magento\Framework\ObjectManagerInterface $objectmanager,
   ...
) 
{
   ...
   $this->_objectManager = $objectmanager;
   ...
}

But when we are using this in any plugin file or any custom module file, we are getting error or its not working. But in case of direct method we are getting solution.

Is there any proper definition, where we have to use direct method of objectManager and where we have to use ObjectManagerInterface ?

Actually when I am trying to get objectManager object in my custom module file I am getting some error and its not working. and with the help of direct method getting proper solution.

2

1 Answer 1

4

This is a misconception, your code should not be aware of the object manager at all. You add the classes that you actually need in the constructor.

So instead of

ObjectManager::getInstance()->get(\Foo\Bar::class)

you use

__construct(\Foo\Bar $foobar)
{
    $this->foobar = $foobar
}

And if you need to create new instances, instead of

ObjectManager::getInstance()->create(\Foo\Bar::class)

you use a factory:

__construct(\Foo\BeerFactory $foobeerFactory)
{
    $this->foobeerFactory = $foobeerFactory;
}

...

$this->foobeerFactory->create()

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