Using Dependency Injection (DI)
Here is the example code to get the product information by product Id and SKU in Magento 2 using dependency injection.
In this, we might need to inject the object of the \Magento\Catalog\Model\ProductRepository class in the constructor of our module’s block class and access it from the view ( .phtml ) file.
Sample File Path: app/code/YourCompanyName/YourModuleName/Block/YourCustomBlock.php
<?php
namespace YourCompanyName\YourModuleName\Block;
class YourCustomBlock extends \Magento\Framework\View\Element\Template
{
protected $_productRepository;
public function __construct(
\Magento\Framework\View\Element\Template\Context $context,
\Magento\Catalog\Model\ProductRepository $productRepository,
array $data = []
) {
$this->_productRepository = $productRepository;
parent::__construct($context, $data);
}
public function getProductById($id) {
return $this->_productRepository->getById($id);
}
public function getProductBySku($sku) {
return $this->_productRepository->get($sku);
}
}
Now, we can use the functions in our view (.phtml) file as follows.
// get product by id
$product = $block->getProductById(15);
// get product by sku
$product = $block->getProductBySku('MT12');
echo $product->getEntityId() . '<br>';
echo $product->getName() . '<br>';
echo $product->getSKU() . '<br>';
echo $product->getPrice() . '<br>';
echo $product->getSpecialPrice() . '<br>';
echo $product->getTypeId() . '<br>';
echo $product->getProductUrl() . '<br>';
Using Object Manager
Here is the example code to get the product information by product id and SKU in Magento 2 using object manager.
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$productRepository = $objectManager->get('\Magento\Catalog\Model\ProductRepository');
// get product by product id
$product = $productRepository->getById(15);
// get product by product sku
$product = $productRepository->get('MT12');
echo $product->getEntityId() . '<br>';
echo $product->getName() . '<br>';
echo $product->getSKU() . '<br>';
echo $product->getPrice() . '<br>';
echo $product->getSpecialPrice() . '<br>';
echo $product->getTypeId() . '<br>';
echo $product->getProductUrl() . '<br>';