In Magento 2 the best way to get a product collection is to use the product repository. Here is an example on how to get a product collection in a block class.
<?php
namespace Experius\CodeBlogProductCollection\Block;
class Products extends \Magento\Framework\View\Element\Template
{
protected $searchCriteriaBuilder;
protected $sortOrder;
protected $productRepository
public function __construct(
\Magento\Framework\View\Element\Template\Context $context,
\Magento\Catalog\Model\ProductRepository $productRepository,
\Magento\Framework\Api\SearchCriteriaBuilder $searchCriteriaBuilder,
\Magento\Framework\Api\SortOrder $sortOrder,
array $data = []
) {
$this->productRepository = $productRepository;
$this->searchCriteriaBuilder = $searchCriteriaBuilder;
$this->sortOrder = $sortOrder;
parent::__construct($context, $data);
}
public function getProductCollection(){
$searchCriteria = $this->searchCriteriaBuilder
->addFilter('type_id','simple','eq')
->addFilter('status',1,'eq')
->setPageSize(10)
->setCurrentPage(1)
->addSortOrder($this->sortOrder->setDirection('DESC')->setField('name'))
->create();
$products = $this->productRepository->getList($searchCriteria);
return $products->getItems();
}
}
