Know everything about Dependency Injection in Magento 2

  •        0

We aggregate and tag open source projects. We have collections of more than one million projects. Check out the projects section.


Magento 2 is no longer a buzzing term. Since Its inception one and a half years ago, developers are in love with its rich technology stack. The following post emphasizes on Dependency Injection (DI), one of the best design patterns that Magento 2 uses.

What is Dependency Injection?

In simple words Dependency means something is dependent on something. For example, there are times when you are dependent on your parents or spouses for a situation or to a certain age similarly in programming. Imagine a situation where you end up creating a class, the class which is highly dependent on the objects. Dependency is what is needed by the class to perform some functions.

Injection on the other hand means to inject something or to provide something needful and all this is done by a third person. Technically speaking, injection is said when it passes off that particular dependency to the dependent object/class. So when we combine the two, the real meaning of Dependency Injection DI is to inject the dependency into the class from another source.

Are you still in a difficult circumstance when to migrate from Magento 1 website to Magento 2? Consult the experts in providing Magento Services.

Dependency Injection Design pattern - Let’s Delve into the Details

Over the course of years, dependency injection has been one of the most significant transformations that occurred till date in Magento 2 development realm. Of course, the codebase of Magento seems to have changed to a great extent and many new things have introduced but nothing beats Dependency Injection concept.

For those who are still confused with the concept, let me provide you a classic example offered by John Munsch. When you go and get things out of a refrigerator for yourself, causing problems might be something that’s inevitable for you. For instance, you may end up leaving the door open or get something which you shouldn’t be having or any other serious issues like not even checking the expiry dates, etc. Thus, you need someone to provide desirable results.

Here in the above-stated example, the child is a collaborating class who needs to rely on his parents, i.e. the foundation class. Dependency injection is more like a win-win situation for everyone as it passes the object to the dependent class, rather than allowing the dependent class to build or find the object right from scratch.

Class dependency

Dependency Injection in Magento 2

First and foremost, we will list out certain types of DI in Magento 2 space.

Dependency Injection

Construction Injection - This type is quite basic in nature, all you have to do is add a parameter in class constructor to inject the dependency. For example, injecting the dependency of customerSession is quite easy when you are willing to get current customer’s data especially in the created class. I mean gone are the days when you were required to write the whole code to get customer data.

Let’s say, for example, take a look at the data block class of custom modules used to get customer’s data and also it uses viewHelper dependency to get customer names.

Code Sample: Data.php (Constructor Injection)

namespace Sparsh\Custom\Block\Data;

class Data extends \Magento\Framework\View\Element\Template
     protected $_customerSession;
     protected $_viewHelper;

     public function __construct(
                      \Magento\Framework\View\Element\Template\Context $context,
                      \Magento\Customer\Model\Session $customerSession,
                      \Magento\Customer\Helper\View $viewHelper
          /* dependency injection of customerSession and viewHelper for Data class */
          $this->_customerSession = $customerSession;
          $this->_viewHelper = $viewHelper;

    public function getCustomer()
         return $this->_customerSession->getData(); /* retrive customer data */

    public function getName()
        /* get customer name with the help of viewHelper object's dependency injection using customer data*/
        return $this->_viewHelper->getCustomerName($this->getCustomer());

Now in the aforementioned example, you have a defined class for custom modules that will successfully fetch data of customerSession. Moreover, here data class has used object customerSession. This is used when we need to call the logic of get (data) method, a method where to get relevant customer section data Magento 2 developers no longer have to write a separate code.

Method Injection
Another way out is the method injection. This is said when a particular method is dependent on a class that needs to be passed anyhow. Now have you understood the concept of Magento Event’s Observer?

Take a look at the code very carefully. Its best example of sales-order-place-after events Order Number Observer.

Code Sample: OrderNumber.php(Method Injection)

 namespace Sparsh\Custom\Observer;

 use Magento\Framework\Event\ObserverInterface;

 class OrderNumber implements ObserverInterface {

           * @param Magento\Framework\Event\Observer $observer
        public function execute(\Magento\Framework\Event\Observer $observer) {
                 $order = $observer->getEvent()->getOrder();
                /* Do Something Here */

To explain things in an easy manner. Here the Magento/Framework/Event/Observer will be served as Dependency injection for OrderNumber class’s execute () method or we can say that execute () method function of Order Number class will be highly dependent on Magento/Framework/Event/Observer to get order object scored.

Why does one need to use it?
DI can be considered as an idiom for Magento 2. However, while creating objects using DI is more work than creating them on a direct basis. So, I would suggest succeeding in the present era, one requires to get themselves into the habit of using DI always.

Although, you can think of creating objects via PHP’s new operator but that doesn’t make DI less of a concept. Try keeping these practices at a minimum and you will soon find that using dependency injection is way more beautiful than explicit instantiation.

What was the problem back then?

By now I am pretty sure you must have understood the concept of DI, i.e. to remove the direct dependency of the objects with class. And to accomplish, the given task we need to use the third class to create objects for that class. I am talking about the object manager in Magento 2.

So, what’s the issue then? Why should we remove this direct dependency? Now imagine you are using a third-party library to calculate tax. As soon as a new update comes, say for example a new library is released which has the taxation class has parameterized. So, the question is how you are going to update your code?

Simple, consider Dependency Injection in Magento 2


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 won’t find any use of a new keyword for creating the object of taxation class. But in the case of a non-parameterized taxation class, managing parameterized class can be quite difficult. Here's when the dependency Injection design pattern comes into play.

So what needs to be done is create a di.xml file in your Magento 2 module and make this code entry:

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

This means when the object manager will create the object of the taxation class it will first and foremost check its type declaration and will add the %newparam% value for its object’s constructor. It may also interest you to know that you can also define any type of argument here in xsi:type like an object, string, int, etc.

Enters the reflection. In simple words reflection means to introspect, examine about self. But when we are talking about programming reflection, it means a PHP library that provides an essential way to check any class member variables, functions, constructor parameters and so more. If simply put, reflection in Magento signifies the class which is going to instantiate.



Henrik Adams is an experienced Magento Developer, who worked with one of the leading Magento Development Company in India – Sparsh Technologies. He likes to write about eCommerce development, web development, marketing, sales and more about current trends.

Subscribe to our newsletter.

We will send mail once in a week about latest updates on open source tools and technologies. subscribe our newsletter

Related Articles

All About Multi-Provider Feature of Angular Version 2.0

  • angular dependency-injection multi-providers

The newly introduced concept of dependency injection in Angular version 2.0 makes it an attractive front-end technology all because of one amazing feature called 'Multi-Providers'. In general, it allows the users to attach certain operations by themselves and a few plugin custom functionality which is not required in our mobile app use case.

Read More

Light4j Cookbook - Rest API, CORS and RDBMS

  • light4j sql cors rest-api

Light 4j is a fast, lightweight and cloud-native microservices framework. In this article, we will see what and how hybrid framework works and integrate with RDMS databases like MySQL, also built in option of CORS handler for in-flight request.

Read More

ETag Easy With RESTEasy

  • resteasy etag http-header rest-api

RESTEasy is a JBoss project that provides various frameworks to help you build RESTful Web Services and RESTful Java applications. It comprises of frameworks for mock, embeddable server, rest client, proxy servers, logging and so on.In this article, we will walk-through ETag implementation and show the behaviour related to ETag done by rest easy framework. Example is developed using RESTEasy 3.7 and deployed in tomcat as RESTEasy framework is portable.

Read More

Getting Started on Undertow Server

  • java web-server undertow rest

Undertow is a high performing web server which can be used for both blocking and non-blocking tasks. It is extermely flexible as application can assemble the parts in whatever way it would make sense. It also supports Servlet 4.0, JSR-356 compliant web socket implementation. Undertow is licensed under Apache License, Version 2.0.

Read More

RESTEasy - A guide to implement CRUD Rest API

  • resteasy rest-api java framework

RESTEasy is a JBoss project that provides various frameworks to help you build RESTful Web Services and RESTful Java applications. It is a fully certified and portable implementation of the JAX-RS 2.1 specification, a JCP specification that provides a Java API for RESTful Web Services over the HTTP protocol. It is licensed under the Apache 2.0 license.

Read More

Getting Started with Spring Batch

  • spring-batch spring-boot batch-processing

The best way to design a system for handling bulk workloads is to make it a batch system. If we are already using Spring, it will be easy to add a Spring Batch to the project. Spring batch provides a lot of boiler plate features required for batch processing like chunk based processing, transaction management and declarative input/output operations. It also provides job control for start, stop, restart, retry and skip processing also.

Read More

GreenMail - Email Test Framework in Java

  • email email-server test automation

In any project there will be a need to send mail out to users. It could be an alert mail, forget password or authentication related mail. Mail is the default communication between the software and the users. As a developer, we can write code, to send out a mail but we need to make sure whether it got successfully received and how the body of mail, Is it the same like what we have sent. GreenMail is a Email test framework which helps to send and receive mails. It is a test framework which supports SMTP, POP3, IMAP including SSL.

Read More

Read and Write PDF using OpenPDF

  • java pdf openpdf create-pdf

OpenPDF is based on a fork of iText version 4. iText is a widely used PDF library but they changed their license and moved to AGPL. In this article, we can see how to read and write to PDF, How to extract text from PDF and How to create password protected PDF.

Read More

Caching using Ehcache Java Library

  • ehcache cache java map key-value

Ehcache from Terracotta is one of Java's most widely used Cache. It is concurrent and highly scalable. It has small footprint with SL4J as the only dependencies. It supports multiple strategies like Expiration policies, Eviction policies. It supports three storage tiers, heap, off-heap, disk storage. There are very few caching products supports multiple tier storage. If you want to scale, you cannot store all items in heap there should be support for off-heap and disk storage. Ehcache is licensed under Apache 2.0. In this article, we can see about basic usage of Ehcache.

Read More

WebSocket implementation with Spring Boot

  • websocket web-sockets spring-boot java

Spring Boot is a microservice-based Java framework used to create web application. WebSocket API is an advanced technology that provides full-duplex communication channels over a single TCP connection. This article explains about how to implement WebSocket using Spring Boot.

Read More

Generate Thumbnail in Java using Thumbnailator library 

  • thumbnail image-processing java

In our work there will be situation where we need to resize the image, generate thumbnails and so on. Users need to have little bit of image processing knowledge to achieve it. We have Java ImageIO APIs to achieve these functionalities. As said, we need to be aware of or spend time in learning these APIs. To help us, Thumbnailator library provides easy fluent style API and generates thumbnail in simple three lines of code.

Read More

Connect to MongoDB and Perform CRUD using Java

  • java mongodb database programming

MongoDB is a popular and widely used open source NoSQL database. MongoDB is a distributed database at its core, so high availability, horizontal scaling, and geographic distribution is quite possible. It is licensed under Server Side Public License. Recently they moved to Server Side Public License, before that MongoDB was released under AGPL. This article will provide basic example to connect and work with MongoDB using Java.

Read More

Quick Start Programming Guide for redis using java client Jedis

  • redis jedis redis-client programming database java

Redis is an open source (BSD licensed), in-memory data structure store, used also as a database cache and message broker. It supports data structures such as strings, hashes, lists, sets, sorted sets with range queries, bitmaps, hyperloglogs, geospatial indexes with radius queries and streams. This article explains about how to communicate with Redis using Java client Jedis.

Read More

Cache using Hazelcast InMemory Data Grid

  • hazelcast cache key-value

Hazelcast is an open source In-Memory Data Grid (IMDG). It provides elastically scalable distributed In-Memory computing, widely recognized as the fastest and most scalable approach to application performance.&nbsp;Hazelcast makes distributed computing simple by offering distributed implementations of many developer-friendly interfaces from Java such as Map, Queue, ExecutorService, Lock and JCache.

Read More

JWT Authentication using Auth0 Library

  • java jwt authentication security

Json Web Token shortly called as JWT becomes defacto standard for authenticating REST API. In a traditional web application, once the user login credentials are validated, loggedin user object will be stored in session. Till user logs out, session will remain and user can work on the web application without any issues. Rest world is stateless, it is difficult to identify whether the user is already authenticated. One way is to use authenticate every API but that would be too expensive task as the client has to provide credentials in every API. Another approach is to use token.

Read More

Compress files faster using Snappy

  • snappy compress zip

Snappy is the fast compression/decompression library from Google. It does not target to reduce compression size but it does faster compression. Most of the open source products use Snappy.

Read More – The First Multithreaded Application Server for PHP written in PHP

  • appserver application-server php

What if you could reliably run PHP without Nginx or Apache, but also without relying on its internal server? What if you could do async operations in PHP with true multi threading, fully taking advantage of multi core processors without hacks or a jungle of callbacks? What if you had drag and drop installation support for your PHAR packaged web apps in an environment identical to its production counterpart? Welcome to – the worlds first open source application server for PHP.

Read More

How to learn from open source projects

  • open-source learning methodology

Students ask this question frequently steps or methodology to learn from open source projects. There is no single answer or steps available. I listed the steps which i follow and i hope this will help for few.

Read More

Getting Started With Django Python Web Framework

  • django python web-framework

Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design. It is pre-loaded with user authentication, content administration, site maps, RSS feeds and many more tasks. Security features provided are cross site scripting (XSS) protection, cross site request forgery protection, SQL injection protection, click-jacking protection, host header validation, session security and so on. It also provides in built caching framework.

Read More

Laravel eCommerce Platform - Bagisto

  • ecommerce shopping laravel php

Nowadays on the web, Shopping is one of the most popular activities. Everyone can shop at their recess, anytime from anywhere. However, this is interesting that anyone can have their pages built to display their favourite products and services.

Read More

We have large collection of open source products. Follow the tags from Tag Cloud >>

Open source products are scattered around the web. Please provide information about the open source projects you own / you use. Add Projects.