Back to Top

Dependency Injection In Adobe Commerce (Magento 2)

Updated 27 September 2024

Magento 2 Dependency Injection (DI) is a cornerstone of its architecture, ensuring flexibility and modularity in the development process.

Developers love Adobe Commerce (Magento 2) for its rich technology stack. Dependency Injection is a key design pattern powering this framework.

However, many still find it challenging to grasp the concept of DI fully. So we’ll try to understand DI as simply as possible.

Introduction

As its name is self-explanatory, lets understand each of them separately:

Dependency simply means that something relies on something else. Just like you’re dependent on your parents, a class in programming can depend on the objects created within it.

Searching for an experienced
Magento 2 Company ?
Find out More

for example:

<?php 

class Product {

  public function getTax($id) {
     $tax = new Taxation();
     return $tax->getCalculateTax($id);
  }   

}

In the example above, you can see a class Product with a method getTax($id), where an object of the Taxation class is instantiated using the new keyword.

Injection simply means to provide something or to inject something by a third person.

In the scenario above, new Taxation() represents the object that should be injected into the class by a third party to decouple the dependency between Product and Taxation.

So 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 Adobe commerce (Magento 2).

Problem

You must be thinking what is the issue with that, why we should remove this direct dependency, things are very easy without it.

Now, imagine you’re using a third-party library to calculate tax, and after an update, a new version is released with the Taxation class now parameterized.

Suppose you instantiate this class 100 times across hundreds of other classes—how would you efficiently update your code in such a scenario?”.

It is a very simple situation there can be much more complex situations like this.

Solution

Now let’s see how DI solves this situation in Adobe commerce (Magento 2):

<?php

class Product {

    protected $_taxation;

    public function __construct(
        \Taxation $taxation
    ) {
        $this->_taxation = $taxation;
    }

    public function getTax($id) {
        return $this->_taxation->getCalculateTax($id);
    }
}

In the above code, there is no use of the new keyword to create an object of the Taxation class. You might be wondering about the case of a non-parameterized Taxation class.

Understanding how to manage parameterized classes is crucial. This is where the beauty of the Dependency Injection pattern, along with OOP concepts like reflection, comes into play.

To handle the above situation you need to first create di.xml file in you Adobe commerce (Magento 2) module, and make this entry:

<type name="/Taxation">
        <arguments>
            <argument name="%newParam%" xsi:type="%anyType%">%Argument%</argument>
        </arguments>
</type>

When the ObjectManager creates the object of the Taxation class, it first checks the type declaration. It then adds the %newParam% value to the object’s constructor.

You can define any type of argument here using xsi:type, such as object, string, int, etc.

you must be thinking how ObjectManager will check the class constructor before creating its object, here comes the use of Reflection.

Reflection means to introspect and examine about self. In programming, Reflection is a PHP library to check class members, functions, and constructor parameters.

By using Reflection, Magento identifies the class it is going to instantiate.

And by doing the above steps you actually solved the problem without having to update the object initialization everywhere.

I hope that the above explanation could have made you understand some basics of DI, I will try to post more on DI as it is huge topic to explain.

For any technical assistance, please reach out to us at support@webkul.com. Additionally, explore a variety of solutions to enhance your Magento 2 store by visiting the Magento 2 extensions store.

If you need expert guidance or want to develop custom features, consider hiring Magento 2 Developers for your project.

Thanks

. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


2 comments

  • Henry Jurk
    • ashutosh srivastava (Moderator)
  • Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home