Magento 2: Get Product collection filter using Service contract.

When you are looking for product collection filter in Magento 2, First thing in your mind come to go with ProductFactory approach.

With ProductFactory way, When you do use a Collection, use a Factory class to instantiate the Collection, as the getCollection() method is deprecated.

How to reso1lved/best way to the deprecated getCollection() issue alternative?

Magento 2 comes with a Service contract design approach and based on Service contract pattern, We need to call the Entity Repository model with the filter set using SearchCriteriaBuilder class.

Using Service Contract is the “best practices” and the “Magento2 Way” of doing things.

We have given a filter to a collection of product SKU start with 24-MB using service contract.

getList() method takes the addAttributeToFilter value using \Magento\Framework\Api\SearchCriteriaInterface.

We have to filter using searchCriteriaBuilder->addFilter() method.

getItems() returns the result from Repository interface with no. of items.

Output for Magento with sample data: