How to use Dependency Injection (DI) in Magento 2

Dependency injection is the idea that a class is given the classes that it needs in the __construct method. Magento uses constructor dependency injection.
In your __construct method, you list classes that you want to be injected and Magento’s DI system will do that for you.

public function __construct( 
      \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
){
      $this->scopeConfig = $scopeConfig;
}

Now we can write methods in this class to get store configuration values.
But… what starts this chain of injections? DI can represent the opposite way to look at architecture: instead of your class taking the initiative to go out and call static classes or initialize new classes, your class simply states what classes it needs and Magento gives your classes what it wants.

The value is that now you can have total control over what is shipped to your class.

  • You can substitute classes with preferences.
  • You can create “new” classes with virtualTypes.
  • You can change constructor arguments out with the type element in etc/di.xml.
  • You can see exactly what other classes your class needs (dependencies).

pub/index.php is the starting point that spins up your Magento instance. The Magento application loads up the DI container. This loads up configuration and a controller. Layout XML is initialized which then renders blocks which render templates which use view models. Through this process, events are triggered and observers listen. Models are loaded from the database.

<?php 
    declare(strict_types=1);
    //app/code/Kaushik/HelloWorld/Controller/View/System.php

    namespace Kaushik\HelloWorld\Controler\View;
    use Magento\Framework\App\Action\Context;
    use Magento\Framework\View\Result\PageFactory;
    use Kaushik\HelloWorld\Action\RetrieveApiValue;
    class System extends \Magento\Framework\App\Action\Action {
        private $actionClass;

        public function __construct( 
            Context $context, 
            RetrieveApiValue $actionClass
        ){
            parent::__construct($context);
            $this‐>actionClass = $actionClass; 
        }

        public function execute() {
            $this->actionClass>getValue();
            // do something else 
        }
    }

In this case, Magento provides an instance of RetrieveApiValue to the above Controller. RetrieveApiValue can request an instance of another class, which can continue the chain.

Leave a Reply