Interfaces in Magento 2
Want to learn everything about M2?
Quickly learn and reference all Magento programming basics, concepts & patterns, even with no prior experience.
If you haven’t used interfaces before, they can be a bit mysterious until you understand why they should be used.
Understanding Interfaces in PHP
An interface in PHP is a contract for a class. It defines what methods a class should have, without providing any actual implementations for those methods. That’s instead the responsibility of the class which implements this interface.
A key point to remember is that a class implementing an interface must implement all the methods defined in the interface. This enforces a level of consistency.
Let’s look back at our Product
class:
<?php declare(strict_types=1); namespace Macademy\\Jumpstart\\Model; class Product { function __construct( private Category $category, ) {} function getCategoryName() { return $this->category->getName(); } }
This code relies on the Category
class. Rather than relying on this class though, it should instead rely on an implementation of this class. So instead of relying on the Category
, we will instead instruct object manager to rely on an implementation of it’s Interface
. So let’s rename this to CategoryInterface
.
<?php declare(strict_types=1); namespace Macademy\\Jumpstart\\Model; use Macademy\\Jumpstart\\Api\\CategoryInterface; class Product { function __construct( private CategoryInterface $category, ) {} function getCategoryName() { return $this->category->getName(); } }
In our code, we are calling the category object’s getName()
method. So at the very least, our interface needs to require the creation of this method.
Here's how we'd create this interface. We’d create a new Api
directory in our module, and then a new PHP file named CategoryInterface.php
. This will be a simple interface, with a single function which must be implemented, named getName()
:
<?php declare(strict_types=1); namespace Macademy\\Jumpstart\\Api; interface CategoryInterface { public function getName(); }
Our Category
class would then implement this interface:
<?php declare(strict_types=1); namespace Macademy\\Jumpstart\\Model; use Macademy\\Jumpstart\\Api\\CategoryInterface; class Category implements CategoryInterface { protected $name; public function getName() { return $this->category->getName(); } }
If we go back to our Product
class, we have a reference to this new CategoryInterface
but Magento does not yet know which class to use when it comes across this interface. In the next lesson, we’ll assign this class preference with XML.