Magento 2 Dependency Injection

YouTube player

Dependency injection:

Hey everyone, and welcome to my channel! Today, we’re diving into the world of Magento 2, and specifically, we’ll be exploring a powerful design pattern called dependency injection.

But before we jump in, let’s imagine you’re baking a cake. You need ingredients, right? Flour, sugar, eggs… the list goes on. Instead of running around the kitchen mixing everything yourself, it would be much easier if someone (or something) handed you the prepared ingredients, one by one, as you need them. That’s the essence of dependency injection!

Why is Dependency Injection Important in Magento 2?

Magento 2 heavily relies on dependency injection, making it a core principle of its architecture.

This brings several advantages:

•   Loose Coupling: Classes become less dependent on each other, as they rely on injected dependencies, not concrete implementations. This makes the code more flexible and easier to maintain.

•   Testability: By injecting dependencies explicitly, you can easily isolate and test individual classes without needing the entire Magento environment.

•   Extensibility: Dependency injection allows you to easily swap out different implementations of the same interface, enabling smooth plugin development and customization.

Assume we have a category and we need to use method getName() from it. We will use dependency injection to use getName() of the category class.

<?php

declare(strict_types=1);

namespace Itcforu\Kickstart\Model;

class Category
{
    public function getName(): string
    {
        return 'Category Name';
    }
}

declare(strict_types=1);

namespace Itcforu\Kickstart\Model;

class Product
{
    private Category $category;

    function __construct(Category $category)
    {
        $this->category = $category;
    }

    function getCategoryName(): string
    {
        return $this->category->getName();
    }
}