162

Ok, so yesterday we had a big talk with other people from the Magento community regarding the direct use of the ObjectManager in classes/templates.

I'm already aware of the reasons why we shouldn't use the ObjectManager directly, quoting Alan Kent :

There are several reasons. The code will work, but it is best practice to not reference the ObjectManager class directly.

  • Because we say so! ;-) (better expressed as consistent code is good code)
  • The code could be used with a different dependency injection framework in the future
  • Testing is easier - you pass in mock arguments for the required class, without having to provide a mock ObjectManager
  • It keeps dependencies clearer - it is obvious what the code depends on via constructor list, rather than having dependencies hidden in the middle of the code
  • It encourages programmers to think about concepts like encapsulation and modularization better - if the constructor gets big, maybe it is a sign the code needs refactoring

From what I've seen in StackExchange, a lot of people tend to go for the easy/short/not recommended solution for example something like this:

<?php 
//Get Object Manager Instance
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();

//Load product by product id
$product = $objectManager->create('Magento\Catalog\Model\Product')->load($id);

Instead of going through the painful but recommended process of:

  • creating a module
  • declaring preferences
  • inject dependencies
  • declare a public method

However, and here comes the dilemma, Magento 2 core files often call the ObjectManager directly. A quick example can be found here: https://github.com/magento/magento2/blob/develop/app/code/Magento/GoogleOptimizer/Block/Adminhtml/Form.php#L57

So here are my questions:

  • Why is Magento doing what they recommend us not to do ? Does that mean there are some cases where we should use the ObjectManager directly? If so, what are those cases?
  • What are the consequences of using the ObjectManager directly?
14
  • 5
    Check this out: magento.stackexchange.com/q/28617/146
    – Marius
    Commented May 26, 2016 at 11:29
  • 3
    Relevant link: mwop.net/blog/2016-04-26-on-locators.html. The relevant bit of it would be The intent of zend-servicemanager is for use as an Inversion of Control container. It was never intended as a general purpose service locator [...]. Which it applies to M2, too. Also check the There are valid use cases section, which, again, applies here, too.
    – nevvermind
    Commented May 26, 2016 at 12:29
  • 4
    There was some period of M2 development when OM was already there, but whole magento was not yet changed to use constructor injection. At that point many people replaced Mage::getSingleton() with ObjectManager::getInstance()->get(). Most of such usages were introduced at that period. Later all Mage::getSingleton() calls were replaced with constructor injection by a tool, but tool did not recognized ObjectManager::getInstance(), so it did not replace it with constructor injection.
    – Anton Kril
    Commented Oct 6, 2016 at 11:03
  • 3
    Possible duplicate of Magento 2 Helper instance Commented Feb 20, 2017 at 12:08
  • 3
    @TejabhagavanKollepara did you read both questions ? There are similar but far from being duplicate from each other Commented Feb 20, 2017 at 12:15

10 Answers 10

119

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
19
  • 6
    I know I should never use it directly but why is Magento doing it ? ^^ Commented May 26, 2016 at 11:41
  • 2
    in your example is for backward compatibility
    – KAndy
    Commented May 26, 2016 at 11:42
  • 1
    What about this one: github.com/magento/magento2/blob/develop/app/code/Magento/… ? Commented May 26, 2016 at 12:02
  • 7
    oh yeah mate I know it is just confusing. Maybe they should have said "don't do it but be aware that we have probably left some mistakes here and there" ;) Commented May 26, 2016 at 20:23
  • 2
    if you have the class of 10 functions, you already have a problem and optional dependency, not a big deal. In any case, you may use proxy for optional dependencies
    – KAndy
    Commented Jul 19, 2016 at 16:03
64

So why does M2 sometimes access object manager directly when we recommend against it?

Brutal answer: M2 is a port of M1 - not a complete rewrite. So don't assume that all the M2 code is perfectly ported yet (unfortunately). Just because you find something in the M2 code base, that does not mean "its the best way to do it". Sometimes it is just "we have not got around to fixing it yet".

Less brutal: As per other responses, sometimes you MUST use it as there is no alternative. Other times it might be for backwards compatibility reasons. And framework code sometimes makes sense using it directly, because it is framework code. But if I had to guess without looking at code, many really should be fixed but it has not been high enough priority to do so yet.

Just remember the good parenting advice: "Kids, do what I say, not what I do!"

3
  • 13
    excellent quote:Kids, do what I say, not what I do!
    – sivakumar
    Commented Jun 1, 2016 at 1:16
  • 1
    That's not how it works kiddo
    – Ansyori
    Commented Jun 1, 2017 at 7:36
  • Is there a Magento 2 recommend way to have a soft dependency problem without object manager? I have a module with a soft dependency on another (it loads another class if the module exists). I can't DI that class in because then DI will fail. I can't even DI a Factory for that class because the factory will fail to DI. Commented Mar 14, 2018 at 14:54
61

You should never use \Magento\Framework\App\ObjectManager::getInstance().
It defeats the purpose of dependency injection. We're back at Mage::getModel().
Object manager should be used only in factories and then as injected in a constructor.

The advantage of using this is less code to write. But this does not make it OK.
The fact that this is still used in the core, is because it didn't get refactored yet. I hope it will be.

19
  • 6
    So we both agree that Magento code is doing it wrong right ? Commented May 26, 2016 at 11:41
  • 15
    right. they are wrong :).
    – Marius
    Commented May 26, 2016 at 11:43
  • I don't think they're using wrong. They're using it when necessary: when dynamic resolving is needed (plugins, especially) and when keeping BC on immediately-deprecated methods.
    – nevvermind
    Commented May 26, 2016 at 12:32
  • 2
    @nevvermind Using a factory. You use di.xml to create a key => class name map and inject that map in to constructor of the factory and use the factory to instantiate the class through objectmanager
    – Marius
    Commented May 26, 2016 at 15:07
  • 2
    @nevvermind But a Magento employee's opinion outranks your opinion. You have an answer above from KAndy that states in bold letter "you should not use the object manager directly": magento.stackexchange.com/a/117103/146 I guess that kind of clears the fog on the issue.
    – Marius
    Commented May 26, 2016 at 15:31
24

Why is Magento doing what they recommend us not to do ? Does that mean there are some cases where we should use the ObjectManager directly ? If so, what those cases ?

Without knowing the full story here is my guess:

During the development of M2 the Magento team at some stage ran an automated script which replaced occurrences of Mage:getModel(), Mage::getSingleton(), $layout->createBlock(), etc. to use the ObjectManager.

Later refactoring should have fixed this to instead use proper dependency injection but there wasn't enough time / resources to convert all occurrences.

Also the Magento team lately seems to use this as an escape mechanism. Instead of breaking an existing implementation (by needing to change the constructor) they simply hide the new dependency via the ObjectManager. I can't say I agree with this approach - writing worse code to avoid a BC break.

What are the direct consequences of using the ObjectManager directly ?

I think your question already includes enough reasons. Generally it creates a hidden dependency, in other words the dependency is in the implementation details and not visible from the constructor alone.

1
  • It is ironic because had there done it properly before releasing to the public the BC wouldn't have been an issue at all
    – scrowler
    Commented May 31, 2016 at 17:50
16

Should not use Object manager directly!

For instance:

\Magento\Framework\App\ObjectManager::getInstance();

also if you are working with event observers or plugins, you should never use it directly.

You could use it in Factories, but except that you should inject the Object Manager in the Constructor first then you can use its object in your method

Preferred to use:

1) declare private object:

private $_objectManager;

2) inject in the constructor and initialize:

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

3) use in some method:

public function create() {
    return $this->_objectManager->create(/* ......... */);
}

This answer is for below Magento 2.2 versions, so please take a note. As per new Magento 2 standards now we can not use even objectManager instance, too. We have to use factory of the object class or repository to get any data.

8
  • Is it a good practice to use it this way?
    – enrico69
    Commented Sep 29, 2017 at 16:04
  • Yes, because magento doesn't allow to use direct objectManager, so you have to use this way! Commented Sep 29, 2017 at 17:23
  • You should also never use it in events (I guess you mean Observers) and plugins. You should inject the objects that you need, not the ObjectManager. Only in a Factory you could use the ObjectManager and then you should indeed inject it instead of calling ::getInstance()
    – 7ochem
    Commented Apr 10, 2018 at 13:38
  • Right, edit the answer @7ochem Commented Apr 16, 2018 at 11:51
  • downvote any answer is not an appropriate way, If you have better knowledge then you can add your own answer or you can edit any other's answer to get better idea and helpful to others. @7ochem Commented Apr 16, 2018 at 11:57
14

The main reason that developers are strongly discouraged from using the Object Manager directly is that direct use of the Object Manager causes the extension not to be installable in compiled production mode.

So it breaks for your customers using production mode, including all customers on Magento Cloud.

It seems like a reasonably large proportion of developers (approximately 75%) do not test their extensions to see if they can be installed in production mode, so do not run into the issues posed by incorrect ObjectManager usage.

As of 2017, the Magento Marketplace runs a compile and install test on all extensions sold through it. If your extension uses the Object Manager directly, it will fail these tests and be rejected from the Marketplace until you resolve this problem and reupload.

2
  • What is release mode? Do you mean production mode?
    – Black
    Commented Apr 27, 2021 at 13:56
  • @Black Is that what the cool kids are calling it? It's been years since I worked for Magento, or cared about it. Call it what you want, the important part of this answer as I remember it was "compiled". Direct use of the OM breaks compilation. Commented Apr 28, 2021 at 17:19
3

You can try by creating an object of objectManager and should not use objectManager directly.

Use something like,

class Example extends \Magento\Framework\View\Element\Template
{
    private $_objectManager;

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

    public function getExample()
    {
        $customerSession = $this->_objectManager->create("Magento\Customer\Model\Session");
        if ($customerSession->isLoggedIn()) {
            $customerData = $customerSession->getCustomer()->getData();
            /*Your logic*/
        }
    }
}
1
  • 4
    If the object manager is a singleton, why would this make a difference? Commented Feb 1, 2019 at 0:50
3

You should not call the object manager directly because the framework handles this automatically. You can see few exceptions that Magento 2 core classes call the ObjectManager directly because this code needs exist for backward compatibility purposes. But, they are not approval of using the ObjectManager directly.

Moreover, if you run:

bin/magento dev:di:info "Magento\Quote\Model\QuoteRepository"

you will get "information on Dependency Injection configuration", but you will not get the information of direct usage of ObjectManager. Also, direct use of its create() function prevents type validation and type hinting that a factory class provides.

0

As of year 2021:

The Magento framework uses the ObjectManager to generate and inject the classes declared in your constructor. Classes should not ask for the ObjectManager itself as a constructor dependency.

You do not call the object manager directly because the framework handles this automatically. Direct use of the create function prevents type validation and type hinting that a factory class provides.

Source

0

Magento addresses these questions in their developer documentation.

Source: https://devdocs.magento.com/guides/v2.4/extension-dev-guide/object-manager.html#usage-rules


Question 1

Why is Magento doing what they recommend us not to do ? Does that mean there are some cases where we should use the ObjectManager directly? If so, what are those cases?

Magento Developer Documentation Answer:

You may notice in the Magento 2 codebase that some core classes still call the ObjectManager directly. This code needs porting or exist for backward compatibility purposes. They are not tacit endorsements of using the ObjectManager directly.


Question 2

What are the consequences of using the ObjectManager directly?

Magento Developer Documentation Answer:

Direct use of the create function prevents type validation and type hinting that a factory class provides.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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