Magento2 API – Benefits of Using Service Contracts

apicrudfactorymagento-2.0service-contract

So as some of you may know, Magento 2 recommended way to deal with models/collections for CRUD actions is to use service contracts.

But still according to the Magento SE Q&A it seems like most people tend to use the model/resource model/collection directly instead.

As an example to load a quote I can do it directly via the factory like this:

$this->quoteFactory->create()->load($quoteId);

Where $this->quoteFactory is an instance of \Magento\Quote\Model\QuoteFactory

But I can also do it via service contract like this:

$this->quoteRepository->get($quoteId);

Where $this->quoteRepository is an instance of \Magento\Quote\Api\CartRepositoryInterface

So my questions is what are the benefits of using service contracts over factories ?

Best Answer

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.

Related Topic