Reading list Switch to dark mode

    Dependency Injection In Magento2

    Updated 6 March 2024

    Magento2 is not new now it’s nearly 5 and a half year till it’s inception, most of the developers love magento2 because of its rich technology stack. Dependency Injection(DI) is one of the design patterns that Magento2 uses, but still some people do not understand exactly what DI is? 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 is dependent on something, like you are dependent on your parents in the same way in programming if we create a class it can be dependent on the objects those are created inside the class, for example:

    <?php 
    
    class Product {
    
      public function getTax($id) {
         $tax = new Taxation();
         return $tax->getCalculateTax($id);
      }   
    
    }

    In the above example you can see a class  “Product” that has a method “getTax($id)” and inside that there is an object  instantiation with new keyword for class “Taxation”, so this ultimately makes Product class dependent on “Taxation” (Product -> Taxation) class, so if it will not found Taxation class then Product class cannot be used too.

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

    Searching for an experienced
    Magento 2 Company ?
    Find out More

    And in the above scenario, new Taxation() is the object that needs to be injected in the class by a third person for the decoupling of the dependency from Product -> 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 Magento2.

    Problem

    You must be thinking what is the issue with that, why we should remove this direct dependency, things are very easy without it. But imagine you are using a third party library to calculate tax and after some update new library released which has the Taxation class parameterized, and suppose its object  is called 100 times inside hundreds of classes then how you are going to update your code, 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 magento2:

    <?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 you can see, there in no use of new keyword for creating the object of taxation class, but you must be thinking, in the case of non-parameterized Taxation class it is ok but how it will manage parameterized class, this is the beauty of dependency injection pattern and some of the oops concepts like reflection this can be managed very easily.

    To handle the above situation you need to first create di.xml file in you magento2 module, and make this entry:

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

    making that entry means that when the ObjectManager will create the object of the Taxation class it will first check its type declaration and will add the %newParam% value for its object’s constructor, you can define any type of argument here in xsi:type like 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, to examine about self, and in programming Reflection is a php library which provides a way to check any class member variables, functions, constructor parameters, so by using Reflection Magento gets to know about the class which 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.

    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