Using Model Factory
public function __construct(
\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,
)
{
$this->_productCollectionFactory = $productCollectionFactory;
}
public function getProductCollection()
{
$collection = $this->_productCollectionFactory->create();
$collection->addAttributeToSelect('*');
$collection->setPageSize(6); // 6 products limit
return $collection;
}
Using Model
public function __construct(
\Magento\Catalog\Model\Product $product
)
{
$this->product = $product;
}
public function getCollection()
{
$collection = $this->product->create()->getCollection();
return $collection;
}
public function loadProduct($id)
{
$product = $this->product->create()->load($id);
return $product;
}
Using Repositories (Service Contracts)
protected $productRepo;
public function __construct(
\Magento\Catalog\Api\ProductRepositoryInterface $productRepositoryInterface
) {
$this->productRepository = $productRepositoryInterface;
}
// $id as product id
public function getProductById($id)
{
return $this->productRepository->getById($itemId);
}
// $sku as product sku
public function getProductBySku($sku)
{
return $this->productRepository->get($sku);
}