Service contract design patterns
In the programming community, a design pattern is a recommended way of writing code that includes when to use, or not use, the pattern. Think of a design pattern as a best practice with conditions.
Design patterns for service contracts tell you which types of interfaces to define, and how and where to define and implement those interfaces.
Service contract data interfaces are now mutable.
Interface types and locations
A service contract must define data interfaces, which preserve data integrity, and service interfaces, which hide business logic from service requestors.
Data interfaces define functions that return information about data entities, return search results, and set validation rules and return validation results. You must define the data interfaces for a service contract in the Api/Data subdirectory for a module .
Service interfaces include management, repository, and metadata interfaces. You must define the service interfaces for a service contract in the Api subdirectory for a module.
Define data interfaces in the Api/Data subdirectory for a module.
For example, the data interfaces for the Customer module are in the /app/code/Magento/Customer/Api/Data subdirectory.
Data search results interfaces
When you pass search criteria to a
getList() call, a search results interface is returned with the search results.
You must define one interface for each data entity
for type hinting purposes. That is, the
getItems() function in the
CustomerSearchResultsInterface returns an array of
CustomerInterface data entities.
getItems() function returns an array of
GroupInterface data entities.
Service interfaces include several interface subtypes:
- Repository interfaces
- Management interfaces
- Metadata interfaces
For file names and coding standards, follow the defined PHP coding standards.
Place service interfaces in the top-level Api directory for a module.
Repository interfaces provide access to persistent data entities.
For example, persistent data entities for the Customer module include Customer, Address, and Group. Consequently, repository interfaces for the Customer module are:
Repository interfaces must provide these functions:
If an ID is not specified, creates a record.
If an ID is specified, updates the record for the specified ID.
Performs a database lookup by ID.
Returns a data entity interface, such as
Performs a search for all data entities that match specified search criteria.
Returns a search results interface that gives access to the set of matches.
Deletes a specified entity. The entity contains the key (ID).
Deletes a specified entity by key (ID).
Each data entity has a corresponding interface. Consequently, the
get() function in the corresponding interface, for example, can return the exact type.
Management interfaces provide management functions that are not related to repositories. For example: