MageDirect

How to implement Service Contracts for custom module in Magento 2

One of the greatest innovations in Magento 2 is Service contracts, which allow third-party developers to safely expand the core functionality, without a deep immersion in the nuances of implementation.

At its heart, Service contracts is a set of PHP-interfaces in the module that provide a well-defined API for other modules and third-party extensions. We can safely rely on the signature of interfaces, as it is unchanged, unlike implementation.

Benefits of using Service contracts:

  • improve the upgrade process
  • strengthen the modular structure of Magento
  • It is possible to follow the principle of programming at the interface level, rather than implementation
  • formalize customization

Let’s see the example how can we implement Service Contracts for the custom module and how can this API be used by other modules.

First of all, we need to create and register a Magento module and add some data to the database.

1. Register new module, in our example, it will be MageDirect_Faq.

 

register new module

 

2. Create custom database table magedirect_faq with faq_id, title, content, created_at, updated_at, is_active columns register

The database table is created within MageDirect/Faq/InstallSchema.php.

Testing data is added within MageDirect/Faq/UpgradeData.php

3. Run the database upgrade command from your Magento root directory:

4. Define interfaces within API directory and their implementation within Model directory

There are following types of interfaces: Data interfaces (API/Data subdirectory) and Service interfaces (API directory).

Data Interface provides access to a module’s entity data.

Let’s see an example of the data interface.

And its implementation:

Service interfaces are divided into several subtypes: Repository interfaces, Management interfaces, Metadata interfaces.

In our example, we add Repository interface. In general, it should have next CRUD- methods:

  • save (data entity interface)
  • getById
  • getList (search criteria)
  • delete (data entity interface)
  • deleteById

FaqRepositoryInterface implementation example

5. Don’t forget to add preference configuration for interfaces to di.xml

6. Now other modules can use faq-repository

Get faq

Delete faq

Get faq list

Save faq

Module example on GitHub

More info in the official documentation:

Was this article helpful?
Dislike 0
Views: 51
Lilya Gogoleva

Lilya GogolevaMagento Developer

Rate us
Please wait...
Bottom Top