Unlocking The Power Of Interfaces In Magento 2!

Interfaces play a vital role in Magento 2 development. Here’s why:

Abstraction: They decouple your code from concrete implementations, making it more flexible and adaptable to changes.

Extensibility: Interfaces promote modularity, allowing third-party developers to extend or modify functionality without affecting your core code.

Testability: Interfaces make it easier to write unit tests by allowing you to mock dependencies.

Service Contracts: Magento 2 extensively uses interfaces to define service contracts. These contracts provide a clear API for modules to interact with each other, enhancing stability.

lets start with the Cateogry class:

class Category implements CategoryInterface

<?php

declare(strict_types=1);

namespace Itcforu\Kickstart\Model;

use Itcforu\Kickstart\Api\Data\CategoryInterface;
class Category implements CategoryInterface
{
    public function getName(): string
    {
        return 'Category Name';
    }
}

note I’m using github copilot

CategoryInterface:

<?php declare(strict_types=1);

namespace Itcforu\Kickstart\Api\Data;

interface CategoryInterface
{
    /**
     * @return string
     */
    public function getName(): string;
}

Product class:

We will use CategoryInteface insetead of the Category Model

<?php

declare(strict_types=1);

namespace Itcforu\Kickstart\Model;

use Itcforu\Kickstart\Api\Data\CategoryInterface;

class Product {

    /**
     * @param Category $category
     */
    public function __construct(
        private CategoryInterface $category,
    ){}

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

in the next lesson we will some xml to assign this using something called a class preference

If you have any question, please write a comment below I will try my best to help you

Thanks for watching if you see this lesson are valuable, please like and subscribe to the channel.