Class preferences and service contracts
Want to learn everything about M2?
Quickly learn and reference all Magento programming basics, concepts & patterns, even with no prior experience.
Defining a Class Preference with XML
XML plays a crucial role in Magento 2 when it comes to dependencies. We can instruct the Object Manager to use the Category
class as the implementation whenever CategoryInterface
is invoked. This is referred to as a class preference. We’ll tell Magento which class is preferred, and it’ll use this to determine which class to substitute in for the interface at runtime.
We'll do this by editing the di.xml
file in our module's etc
directory:
<?xml version="1.0"?> <config xmlns:xsi="<http://www.w3.org/2001/XMLSchema-instance>" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd"> <preference for="Macademy\\Jumpstart\\Api\\CategoryInterface" type="Macademy\\Jumpstart\\Model\\Category" /> </config>
The preference
node in the XML document essentially says:
"Whenever you see someone requiring theCategoryInterface
, give them an instance of theCategory
instead."
And that's it! Our changes will be applied as soon as the cache is cleared. The code can now rely on an interface instead of a class, and as long as that interface is obeyed, any class can be swapped in and out.
Why service contracts?
Magento uses a service contract-based architecture, where an interface defines all the capabilities that a module can offer. Instead of directly interacting with a module, you do so via interfaces. This reduces coupling between modules and makes it easier to tweak or replace the behavior of a module.
Implementing the interface ensures that all instances of the Category
class provide a consistent method to retrieve the category name associated with that category.
But, here's where interfaces shine. Suppose, in the future, you decide to change the way category names are fetched. Maybe you now want to fetch this information from a third-party API or a database, rather than a string.
As long as the changes don't alter the type of data returned by the methods in CategoryInterface
, you can modify your Category
implementation without breaking anything in the rest of your application. Any part of your system using CategoryInterface
will work just fine as long as it gets the data it expects.
Implementing interfaces in your Magento 2 classes ensures your code is extensible and maintainable. It also allows third-party developers to easily tweak or modify an implementation while retaining compatibility with other code.