What is dependency injection in Magento 2?
What is dependency injection in Magento 2?
What is dependency injection in Magento 2?
Dependency Injection
Dependency Injection means to remove the direct dependency of the objects with class
and use a third class to create objects for that class which is ObjectManager in Magento2.
================================================================================
class CustomInfo
{
private $custom;
public function __construct($customdataone, $customdatatwo)
{
$this->customer = new Custom($customdataone, $customdatatwo);
}
public function getCustomdata()
{
return $this->custom;
}
}
===============================================================================
class CustomInfo
{
private $custom;
public function __construct(custom $custom)
{
$this->custom = $custom;
}
public function getCustom()
{
return $this->custom;
}
================================================================================
A dependency is an object that can be used
and an injection is the passing of a dependency to a dependent object that would use it
There are three types of Dependency Injection: Constructor Injection, Setter Injection and Interface Injection.
Magento 2 uses Constructor Injection
Dependency Injection is an alternative to Mage class used in Magento 1.
Magento 2 uses Automatic Dependency Injection.
Magento 2 uses Constructor Dependency Injection.
Using Constructor for DI is a must.
Instance Configurations can be specified at three levels:
app/etc/di/*.xml
{moduleDir}/etc/di.xml
{moduleDir}/etc/{areaCode}/di.xml
Dependency Injection is a great way to reduce tight coupling between application codebase.
Rather than hard-coding dependencies, you can inject the list of object that a class may need.
Dependency Injection also enables you to manage future changes and other complexity in your codes.