Magento Fundamentals Part 1: Why We Shouldn't (Almost Never) Use the Object Manager
This article is the first of a series inspired by some basic knowledge required for developing on Magento 2.
After more than five years since the release of Magento 2.0 — and plenty of available documentation — these may seem like obvious topics. Still, it’s not so: Every day we come across third-party code that demonstrates the opposite.
What is the Object Manager?
The Object Manager is an object that is used by the framework to instantiate objects and pass them as parameters to the constructor of other classes.
A synonym of the verb "pass" is "inject"; that’s why objects passed by the Object Manager are usually called "injectable objects." The objects passed to the constructor of a class represent its dependencies; indeed, we speak of "dependency injection," abbreviated as DI.
Let’s see an example.
In order for TheMostUselessClass to access to system configuration, we will declare a dependency from ScopeConfigInterface in its constructor, like shown below:
<?php declare(strict_types=1); use \Magento\Framework\App\Config\ScopeConfigInterface; class TheMostUselessClass { protected $config; public function __construct(ScopeConfigInterface $config) { $this->config = $config } }
Let’s focus on the fact that ScopeConfigInterface is an interface and we know that an interface can’t be instantiated.
Thus, the Object Manager should instantiate a class that implements ScopeConfigInterface. To identify the proper class, it will lookup in a map obtained by di.xml files composition. Going more in-depth on how the map is built is out of the scope of this article.
Depending on interfaces (or abstractions) rather than on concrete classes is called "dependency inversion principle" and is used to write less coupled code.
Finish reading on Bitbull.it.