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.

<?php
namespace Rbj\ProductServiceContract\Model;

use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Framework\Api\SearchCriteriaBuilder;

class ProductServiceContract
{
	/**
     * @var ProductRepositoryInterface
     */
    protected $productRepository;

    /**
     * @var SearchCriteriaBuilder
     */
    protected $searchCriteriaBuilder;

    public function __construct(
        ProductRepositoryInterface $productRepository,
        SearchCriteriaBuilder $searchCriteriaBuilder
    ) {
        $this->productRepository = $productRepository;
        $this->searchCriteriaBuilder = $searchCriteriaBuilder;
    }

    /**
     * Load products by skus.
     *
     * @return array
     */
    public function filterProducts()
    {
        $skuStartWith = '24-MB';

        $this->searchCriteriaBuilder->addFilter(
            'sku',
            $skuStartWith."%",
            'like'
        );

        $products = $this->productRepository->getList($this->searchCriteriaBuilder->create())
            ->getItems();

        $name = [];
        if ($products) {
            foreach ($products as $product) {
                $name[] = $product->getName();
            }
        }
        return $name;
    }

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:

Joust Duffle Bag
Fusion Backpack
Crown Summit Backpack
Strive Shoulder Pack
Wayfarer Messenger Bag
Rival Field Messenger