In older extensions or inherited Magento code, you may find direct calls to the ObjectManager. A regular expression makes it easy to search for those calls throughout the codebase.

For example, the search may find:

The regular expression accounts for different amounts of whitespace around :: and before the opening parenthesis. The option -R performs a recursive search, -n prints line numbers, and -P enables grep’s Perl-compatible regular expressions.

You can also look for subsequent calls through a variable called $objectManager :

In custom Magento code, direct ObjectManager use is generally Bad Practicenot recommended. The main reason is that it hides a class’s dependencies. You cannot see which services a class needs from its constructor, because it fetches them later from the ObjectManager.

That makes the code harder to understand and test. With dependency injection, you can replace a dependency with a mock object in a unit test. If a class retrieves the service itself from the global ObjectManager, the test must also account for that hidden access.

Changes become more difficult as well. A class that takes five services in its constructor clearly declares its dependencies. If it fetches those services across several methods, you must read the entire class to find them.

It is cleaner to pass dependencies through the constructor:

Magento then resolves the concrete implementation through dependency injection configuration. Preferences, proxies, plugins and other ObjectManager mechanisms still work, but your class does not need to know how a dependency is constructed.

The ObjectManager itself is not inherently bad: Magento relies on it internally. The problem is directly using it throughout application code, turning dependency injection into a hidden service locator.

Finding Direct ObjectManager Usage in Code
Need help implementing this solution, or still looking for the right solution to your Magento problem? Get in touch and I will be happy to help with your Magento project!
Tags: