Pregunta

What types of Injection methods does Magento 2 support?

I am aware about,

  • Constructor Injection - consider as a Injection.
  • Method Injection - consider as a Injection.

BUT

  • And Interface and Model preference from di.xml should be consider as Injection ?

<preference for="Vendor\Module\Api\ManagementInterface" type="Vendor\Module\Model\Management" />

Does it consider as a Injection ?

Note : If you read Constructor injection in Magento dev docs - It says Magento uses the di.xml file to determine which implementations to inject into the Builder class.

¿Fue útil?

Solución

preference from di.xml

definitly not call that injection that's called implementation mapping.

setter injection

yes. that's DI

Otros consejos

  1. Constructor Injection

For example, I have a Helper class that can be found in Namespace/ModuleName/Helper/Data.php file with the following code:

<?php
namespace Namespace\ModuleName\Helper;
use \Magento\Framework\App\Helper\AbstractHelper;
class Data extends AbstractHelper
{
       public function HelperDemo()
       {
               //Do Something Here
       }
}

In the above Helper Class, I have created a function HelperDemo() that can be called anywhere in Magento 2 using the Constructor Injection.

<?php
class DependentClass
{
       public function __construct(Namespace\ModuleName\Helper\Data $helper)
       {
               $this->helper = $helper;
       }
       public function MyFunction()
       {               $this->helper->HelperDemo();
       }
}

In the above code sample, the DependentClass declares its dependency on the Helper class in its constructor. This way I can call the HelperDemo() function anywhere within the class.

  1. Method Injection

Method injection is another type of ID used in Magento 2, which passes the dependency as a method parameter to use it in the class. Method injection can be used best when the dependency may vary on each method call. When an object requires performing specific actions on a dependency that cannot be injected, it is recommended to use the Method Injection.

<?php
namespace Namespace\ModuleName\Observer\Product;
use Magento\Framework\Event\ObserverInterface;
class Data implements ObserverInterface
{
    /**
     * @param Magento\Framework\Event\Observer $observer
     */
    public function execute(Magento\Framework\Event\Observer $observer)
    {
        //Do Something Here
    }
}

In the above example code for Method Injection, note that the execute() method/function in Data class is dependent on the Magento\Framework\Event\Observer class.

There are three types of Injections Methods Magento2 supports :

  • Constructor Injection
  • Setter Injection
  • Interface Injection
Licenciado bajo: CC-BY-SA con atribución
No afiliado a magento.stackexchange
scroll top