When you are looking for a product collection filter in Magento 2, the first thing in your mind come to go with the 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 resolve/best way to the deprecated getCollection() issue alternative?
Magento 2 comes with a Service contract design approach and based on the Service contract pattern, We need to call the Entity Repository model with the filter set using SearchCriteriaBuilder class.
Using Service Contract is the “best practice” 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 */ private $productRepository; /** * @var SearchCriteriaBuilder */ private $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 starting with 24-MB using a 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 the 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