Magento 2: what are the benefits of using service contracts?

Benifits of using service contracts, (as per Magento 2 understanding)

Service contracts have a number of important functions for Magento 2, such as:

  • Upgrading modules becomes easy.

  • Simplify customizations to the module without digging into the core files.

  • Reduce the conflict between modules in the system.

  • Magento upgrades are safer using service contract.

  • For services will remain unchanged within the new releases of it, making upgrade in future are easy for existing module.

  • For model/collections this case are not true within new releases.


I think the greatest benefit is that modules can determine which functionality can be used by other modules. In Magento 1 you had helpers that where often kind of misused for this purpose (but that's a whole other discussen), but in Magento 2 your module can provide functionality to other modules (for example by 3rd party developers) and have it separated and self-contained.

Dependency Injection provides a system where you can use an interface in your construction so you only have access to those public methods.

Some examples:

Want to link a product to multiple categories? Use \Magento\Catalog\Api\CategoryLinkManagementInterface:

$this->categoryLinkManagement->assignProductToCategories(
    $sku,
    $categoryIds
);

Want to increase a products' stock quantity? Use Magento\CatalogInventory\Api\StockManagementInterface:

$this->stockManagement->backItemQty(
    $productId,
    $itemsToReceive
);

These two example show perfectly the proper use of service contracts. Besides that, they provide a uniform interface to communicate with:

  • Other Modules (as described above)
  • Console Commands
  • API Calls
  • etc.

Benefits of service contract:

  • Enhance the modularity of Magento

  • Ensure a well-defined, durable API that other modules and third-party extensions can implement

  • Make it easy to configure services as web APIs.

  • Data entities reveal a simpler data model than the data model in an underlying relational database schema

  • Use different storage technologies for different data collections