Class preferences and service contracts

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:

<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 the CategoryInterface, give them an instance of the Category 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.

Complete and Continue  
Extra lesson content locked
Enroll to access all lessons, source code & comments.
Enroll now to Unlock