This website uses cookies

Our website, platform and/or any sub domains use cookies to understand how you use our services, and to improve both your experience and our marketing relevance.

📣 Try the fastest hosting platform with pay-as-you-go pricing & 24/7 expert support! MIGRATE NOW →

What is Magento 2 Dependency Injection And How to Use It

Updated on December 20, 2021

4 Min Read
Dependency Injection Magento 2

In programming languages, a dependency is known as the object which is needed by a class to perform some functions. Injection is the passing of that particular dependency to a dependent object/class. The real meaning of Dependency Injection is to inject the dependency into the class from another source. In this post, we’ll discuss Magento 2 Dependency Injection.

Understanding Magento 2 Dependency Injection

For example, if you have defined a Class in Magento 2 that fetches some data by using Magento 2 Helper Class, we can say that your Class has a dependency of that Magento 2 Helper Object.

Still confused? Let’s take a simple scenario. You are constructing a house, and you begin with the pillars and walls. At the entry point, when you think to get the main gate, what will you do? Would you start building a custom gate out of wood, iron, or other raw materials? Or would you take it directly from a vendor and install it, hassle free?
That’s absolutely right! The most pragmatic approach is to buy the ready-made gate from a vendor and to simply install it. And that is what Dependency Injection does. It decouples your class from the construction of its dependency.

class Customer
{
    private $firstName;
    private $lastName;
 
    public function __construct($firstName, $lastName)
    {
        $this->firstName = $firstName;
        $this->lastName = $lastName;
    }
 
    public function getFirstName()
    {
        return $this->firstName;
    }
 
    public function getLastName()
    {
        return $this->lastName;
    }
}

class CustomerInfo
{
    private $customer;

    public function __construct($customerFirstName, $customerLastName)
    {
        $this->customer = new Customer($customerFirstName, $customerLastName);
    }
 
    public function getCustomer()
    {
        return $this->customer;
    }
 }

There is nothing wrong with the above code. It will return the first & last name without any issues. But the Customer class is tightly coupled with the CustomerInfo class. If you add a new parameter to the constructor of Customer class, then you have to modify every class where you had created a Customer object with the new operator, which subjects it to a tedious and lengthy process, especially when it comes to the large applications.

Magento 2 Dependency Injection solves these issues by injecting the dependencies through the dependent class’ constructor. The result is highly maintainable code which can be used in long-term projects. It might look like this:

class Customer
{
    private $firstName;
    private $lastName;
 
    public function __construct($firstName, $lastName)
    {
        $this->firstName = $firstName;
        $this->lastName = $lastName;
    }
 
    public function getFirstName()
    {
        return $this->firstName;
    }
 
    public function getLastName()
    {
        return $this->lastName;
    }
}

class CustomerInfo
{
    private $customer;

    public function __construct(Customer $customer)
    {
        $this->customer = $customer;
    }
 
    public function getCustomer()
    {
        return $this->customer;
    }
 }

In the above code, instead of instantiating dependency with the new operator, we defined it in a __construct parameter. It is known as Automatic Dependency Injection. Yes! The previous example might be easy for you, but believe me, we don’t need them in latest programming techniques.

Say Goodbye to hosting hassle!

Streamline your Magento 2 development process with cloudways developer friendly managed hosting.

What Are the Different Types of Dependency Injection in Magento?

By using Automatic Dependency Injection (ADI), the object doesn’t need to look for another dependent object. There are three types of Automatic Dependency Injections:

  • Constructor Injection: The most common way to inject dependencies is via a class’s constructor. To do this, you need to add an argument to the constructor signature to accept the dependency.
  • Setter Injection: Another possible method to inject a dependency into a class is by adding a setter function that takes the dependency.
  • Interface Injection: The interface injection defines and uses interfaces for the dependency injection.

Magento 2 uses Automatic Dependency Injection (ADI) which is further derived to the Constructor Injection. It means in Magento 2, passing the objects in the constructor’s parameters will help you follow the injection rules. Dependency Injection in Magento 2 is an alternative to the Mage Class method of Magento 1. The below example will give you an idea that how it will look like in Magento 2.

Helper Class in Magento 2 (Data.php):

namespace Namespace\Module\Helper;

class Data extends \Magento\Framework\App\Helper\AbstractHelper
{
    public function HelperFunc()
    {
        return 1;
    }
}

Calling HelperFunc() using DI:

class ClassName
{
    public function __construct(\Namespace\Module\Helper\Data $helper)
    {
        $this->helper = $helper;
    }
    public function func()
    {
        $this->helper->HelperFunc();
    }
}

In above code class, you can see how Dependency is injected into the constructor of the class. You can use this method anywhere in Magento 2.

Why Magento 2 Dependency Injection is Preferred Over Object Manager?

The Object Manager can also do this magic. We can call the create() method of ObjectManager, to create the object for your class, gets and passes the value for the constructor parameter from instance configuration (di.xml) files. But you should never use ObjectManager!!

ObjectManager defeats the purpose of Dependency Injection. The advantage of using ObjectManager is less code to write, but it doesn’t follow the Magento 2 Development Processes and also creates the hidden dependencies which are not required.

It is still used somewhere in the core of Magento 2, but it will get refactored soon. So, the best recommendation is, DO NOT USE THE OBJECTMANAGER. It is a good practice to know what the code depends on, rather than having hidden dependencies in the middle of the code. That is why Magento 2 Dependency Injection is preferred by the structure.

Conclusion

It is necessary to follow the code patterns while doing development on Magento 2. Magento Community recommends using Magento 2 Dependency Injection rather than ObjectManager. It was a short introduction of Dependency Iinjection, Automatic Dependency Iinjection, Constructor Injection, and Object Manager in Magento 2.

There is a lot more to learn about each topic very deeply. Stay in touch for more. 🙂 Have any questions? Write in the comments section and I will get back to you!

Share your opinion in the comment section. COMMENT NOW

Share This Article

Abdur Rahman

Abdur Rahman is the Magento whizz at Cloudways. He is growth ambitious, and aims to learn & share information about Ecommerce & Magento Development through practice and experimentation. He loves to travel and explore new ideas whenever he finds time. Get in touch with him at [email protected]

×

Get Our Newsletter
Be the first to get the latest updates and tutorials.

Thankyou for Subscribing Us!

×

Webinar: How to Get 100% Scores on Core Web Vitals

Join Joe Williams & Aleksandar Savkovic on 29th of March, 2021.

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Want to Experience the Cloudways Platform in Its Full Glory?

Take a FREE guided tour of Cloudways and see for yourself how easily you can manage your server & apps on the leading cloud-hosting platform.

Start my tour

CYBER WEEK SAVINGS

  • 0

    Days

  • 0

    Hours

  • 0

    Mints

  • 0

    Sec

GET OFFER

For 4 Months &
40 Free Migrations

For 4 Months &
40 Free Migrations

Upgrade Now