Dependency injection (DI) is a design pattern that allows you to inject objects into a class, rather than creating them inside the class. This allows you to decouple the class from its dependencies, making it more flexible and easier to test.
In Magento 2, you can use dependency injection by adding the required objects as constructor arguments in your class, and then using the __construct
method to inject them into the class. For example:
class MyClass
{
protected $curl;
public function __construct(
\Magento\Framework\HTTP\Client\Curl $curl
) {
$this->curl = $curl;
}
public function makeRequest()
{
$this->curl->get('https://www.example.com');
}
}
In this example, the MyClass
class depends on the Curl
class to make HTTP requests. By using dependency injection, we can inject the Curl
class into the MyClass
class and use it without having to create it inside the class.
Object Manager is a class in Magento 2 that is responsible for creating and managing objects in the system. It uses a registry to store objects, so that they can be reused instead of being created multiple times.
To use the object manager, you can use the create
method to create an object, or the get
method to retrieve an existing object from the registry. For example:
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
// Create a new object
$curl = $objectManager->create('Magento\Framework\HTTP\Client\Curl');
// Get an existing object from the registry
$curl = $objectManager->get('Magento\Framework\HTTP\Client\Curl');
While object manager is a powerful tool, it is generally recommended to use dependency injection instead, as it makes your code more flexible and easier to test. Object manager is more suited for situations where you need to create objects on the fly, or when you don’t have access to the class constructor (e.g. in a plugin).