Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 42 ยท Data and the Database

Service Contracts and Repositories

Learn Magento service contracts, API and data interfaces, repositories, why modules should not call models directly, and extension attributes, with runnable stand-ins.

You can read and write Magento data with models, resource models and collections, as shown in the previous lessons. Yet if you look at how core modules talk to each other, they almost never do that. The checkout asks a repository for a product. The REST API calls a repository to save a customer. Third-party modules are told in the documentation to use interfaces, not classes. This set of rules is called service contracts.

A service contract is a promise: "this interface will keep working across releases, whatever classes sit behind it." This lesson explains the two kinds of interface involved, shows what a repository looks like, explains why using models directly is risky, and introduces extension attributes. The Magento code is read-only. The runnable stand-ins implement the pattern in plain PHP on SQLite so you can see how a consumer depends only on an interface and survives a change of implementation.

What a service contract is

A service contract consists of two groups of interfaces, both in your module:

  • Service (API) interfaces in Api/, such as NoteRepositoryInterface. They define operations: getById, save, delete, getList.
  • Data interfaces in Api/Data/, such as NoteInterface. They define the shape of the data: getTitle(), setTitle(), and so on.

Another module, a REST client or your own controller depends on these interfaces only. The real implementation (a model, a resource model, a collection) can change without breaking any caller.

flowchart LR
    C1["Controller"] --> I["NoteRepositoryInterface<br/>(Api/)"]
    C2["REST API"] --> I
    C3["Other module"] --> I
    I -->|"di.xml preference"| R["NoteRepository"]
    R --> M["Model + resource model + collection"]
    R --> D["NoteInterface<br/>(Api/Data/)"]

Callers see only interfaces. The preference in di.xml chooses the implementation (see Preferences and Interfaces in di.xml).

The @api annotation in the interface's docblock marks it as a stable, public contract. Magento follows semantic versioning for @api code, so a method signature will not change in a minor release. Everything else in a module is implementation detail and may change at any time.

The interfaces

Here is a typical pair, shortened. They are real Magento-style code, read-only.

PHP
<?php
// Acme/Note/Api/Data/NoteInterface.php
namespace Acme\Note\Api\Data;

/**
 * @api
 */
interface NoteInterface
{
    public const NOTE_ID = 'note_id';
    public const TITLE = 'title';
    public const BODY = 'body';

    /** @return int|null */
    public function getNoteId();

    /** @param int $noteId @return $this */
    public function setNoteId($noteId);

    /** @return string */
    public function getTitle();

    /** @param string $title @return $this */
    public function setTitle($title);
}
PHP
<?php
// Acme/Note/Api/NoteRepositoryInterface.php
namespace Acme\Note\Api;

/**
 * @api
 */
interface NoteRepositoryInterface
{
    /**
     * @param int $noteId
     * @return \Acme\Note\Api\Data\NoteInterface
     * @throws \Magento\Framework\Exception\NoSuchEntityException
     */
    public function getById($noteId);

    /**
     * @param \Acme\Note\Api\Data\NoteInterface $note
     * @return \Acme\Note\Api\Data\NoteInterface
     * @throws \Magento\Framework\Exception\CouldNotSaveException
     */
    public function save(\Acme\Note\Api\Data\NoteInterface $note);

    /**
     * @param \Magento\Framework\Api\SearchCriteriaInterface $searchCriteria
     * @return \Acme\Note\Api\Data\NoteSearchResultsInterface
     */
    public function getList(\Magento\Framework\Api\SearchCriteriaInterface $searchCriteria);

    /**
     * @param \Acme\Note\Api\Data\NoteInterface $note
     * @return bool
     * @throws \Magento\Framework\Exception\CouldNotDeleteException
     */
    public function delete(\Acme\Note\Api\Data\NoteInterface $note);
}

You may wonder why the docblocks are so detailed and why return types are in comments. The reason is the web API layer. Magento reads these docblocks by reflection to know the types for REST and SOAP requests and responses, so @param and @return must give fully qualified class names. Newer code may add native types as well, but the docblocks remain the source for the API layer.

The implementation is a normal class. The model implements the data interface, and the repository implements the API interface:

PHP
// Acme/Note/Model/NoteRepository.php (read-only, shortened)
class NoteRepository implements NoteRepositoryInterface
{
    public function __construct(
        private readonly NoteFactory $noteFactory,
        private readonly ResourceModel\Note $resource,
        private readonly NoteSearchResultsInterfaceFactory $searchResultsFactory,
        private readonly CollectionProcessorInterface $collectionProcessor,
        private readonly CollectionFactory $collectionFactory
    ) {
    }

    public function getById($noteId)
    {
        $note = $this->noteFactory->create();
        $this->resource->load($note, $noteId);
        if (!$note->getId()) {
            throw new NoSuchEntityException(__('Note with id "%1" does not exist.', $noteId));
        }
        return $note;
    }

    public function save(NoteInterface $note)
    {
        try {
            $this->resource->save($note);
        } catch (\Exception $e) {
            throw new CouldNotSaveException(__('Could not save the note: %1', $e->getMessage()));
        }
        return $note;
    }
    // delete() and getList() follow the same pattern; getList() uses the collection
    // processor to apply SearchCriteria and returns the search results object.
}

A di.xml preference binds the interfaces to the classes: NoteRepositoryInterface to NoteRepository, and NoteInterface to the model Note (Preferences and Interfaces in di.xml). The repository's getList hands a SearchCriteria to the collection (Collections, Filters and SearchCriteria).

Look at what the repository adds to a raw resource->load():

  1. A clear failure: a missing entity throws NoSuchEntityException, not an empty model you must remember to check.
  2. Translated exceptions: storage errors become CouldNotSaveException, which the API layer knows how to convert into a proper HTTP response.
  3. A stable surface: callers do not know there is a resource model at all.

A repository you can run

The first stand-in has the same structure. NoteInterface and NoteRepositoryInterface are the contract, Note and SqliteNoteRepository are the implementation, and NoteReport is a consumer that knows only the interfaces. The exception types mimic Magento's.

PHP Stand-in: interface, repository, consumer

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The consumer never mentions PDO, SQL or the table. It also handles the failure through a named exception instead of testing an empty object.

Why not use models directly?

Imagine another module calls $noteFactory->create()->load(5) and $note->getData('title'). It now depends on several things that are not promises:

  • the exact class name of the model, which a refactoring may rename;
  • the magic data keys, which a new version may change;
  • that load() exists and behaves as it did (it is deprecated);
  • the table structure, if it filters through the collection.

With a repository interface, you can replace the storage (for example, move the table, add a cache, or fetch from an external service) and callers keep working. Plugins on the repository (Plugins (Interceptors)) also give other modules a safe extension point: a plugin on NoteRepositoryInterface::save runs for every caller, whether it is a controller, the REST API or a cron job. In addition, the web API can expose a repository directly through webapi.xml with no controller code (The REST API).

Services, not storage, are the stable layer. Inside your own module, using the resource model for a quick internal task is acceptable; across module boundaries, use the contract.

Extension attributes at a glance

What if module B wants to add data to module A's entity, such as a "gift note" on an order or a "loyalty tier" on a customer, without changing A's database table or interface? Magento's answer is extension attributes.

An entity that implements ExtensibleDataInterface gets a getExtensionAttributes() method that returns a generated object. Module B declares its attribute in XML:

XML
<!-- Beta/Loyalty/etc/extension_attributes.xml (read-only) -->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:Api/etc/extension_attributes.xsd">
    <extension_attributes for="Acme\Note\Api\Data\NoteInterface">
        <attribute code="loyalty_points" type="int"/>
    </extension_attributes>
</config>

During compilation Magento generates a NoteExtensionInterface with getLoyaltyPoints() and setLoyaltyPoints(). Declaring the attribute does not fill it. To load and save it, module B adds a plugin to the repository's getById, getList and save (Plugins (Interceptors)). The web API then includes the attribute in responses under extension_attributes. Extension attributes are the standard route for third-party data on core entities. Treat them as read/write bags that need plugin code to be populated.

The second stand-in is a toy of that idea. A "plugin" function wraps the repository to attach extra data on read and persist it on save, while the core note class knows nothing about it.

PHP Stand-in: extension attributes added by a decorator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Module A's note class and repository stayed untouched. Module B added a value on the way in and out.

Practical guidance

  • Write the contract first when an entity will be used across modules, by the API or by third parties. Skip it for purely internal helper tables.
  • Keep data interfaces small and free of business logic. They describe data.
  • Document every @param and @return with full class names if the interface is exposed through webapi.xml.
  • Throw Magento's exception types (NoSuchEntityException, CouldNotSaveException, LocalizedException) so the framework can translate them into useful API responses.
  • Never change a published @api interface. Add a new method in a new interface or a new version.
  • Depend on interfaces in your constructors. The object manager resolves them through preferences (The Object Manager and Constructor Injection).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What are the two kinds of interfaces in a service contract?

    API interfaces in Api/ define operations, and data interfaces in Api/Data/ define data. Callers depend only on them.
  2. 2. Why should another module use NoteRepositoryInterface instead of the Note model class?

    Implementation classes can change between releases. The contract is what is kept stable.
  3. 3. Why do Magento API interface docblocks include fully qualified @param and @return types?

    REST and SOAP use reflection of the docblocks to know the data types, so they must be explicit.
  4. 4. What does declaring an extension attribute in extension_attributes.xml do on its own?

    The XML declares the attribute and generates its getter and setter. A plugin on the repository populates and persists it.
  5. 5. What should a repository do when an entity does not exist?

    A named exception makes the failure explicit, and the web API layer can turn it into the right HTTP response.

Summary

  • A service contract is a set of @api interfaces: API interfaces (repositories) and data interfaces (entity shape).
  • Implementation classes (models, resource models, collections) sit behind a di.xml preference and can change freely.
  • Repositories give clear failures, translated exceptions and a single safe extension point for plugins.
  • Docblock types matter because the web API reads them by reflection.
  • Extension attributes let other modules add data to an entity; plugins on the repository fill and save them.
  • Use the contract across module boundaries, and keep published @api interfaces unchanged.

Next: EAV: Entity-Attribute-Value