0

I'm using following code:-

Mage::getModel('catalog/product')

Same code I want to use for Magento2, how can I achieve?

0

Magento 2 uses Dependency Injection. There's a couple of different ways to load a product via Magento 2, but the best practice is to use a Service Contract, which in this case is \Magento\Catalog\Api\ProductRepositoryInterface. Because Magento 2 uses dependency injection there is a preference setup for the aforementioned interface which lets Magento know which Class that implements the interface should be invoked (\Magento\Catalog\Model\ProductRepository).

Note you can also use Product Model Factory Class (\Magento\Catalog\Model\ProductFactory) and the Product Resource Model (\Magento\Catalog\Model\ResourceModel\Product) to load a product, but it's not best practice.

To achieve something similar to Magento 1 functionality you'd do something like this for a Block class.

<?php 

namespace Vendor\Namespace\Block;

use Magento\Framework\View\Element\Template;
use Magento\Framework\View\Element\Template\Context;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Model\ProductFactory;
use Magento\Catalog\Model\ResourceModel\Product as ProductResource;

class MyBlock extends Template
{
    protected $_productRepository;
    protected $_productFactory;
    protected $_productResource;

    public function __construct(
        Context $context,
        ProductRepositoryInterface $productRepository,
        ProductFactory $productFactory, 
        ProductResouce $productResource
        array $data = [])
    {
        $this->_productRepository = $productRepository;
        $this->_productFactory = $productFactory;
        $this->_productResource = $productResource;
        parent::__construct($context, $data);
    }

    // BEST PRACTICE
    public function getProductUsingServiceContract($sku)
    {
        return $this->_productRepository->get($sku);
    }

    public function getProductUsingFactoryAndResouceModel($sku)
    {
        $product = $this->_productFactory->create();
        $this->_productResource->load($product, $product->getIdBySku($sku));
        return $product;
    }

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.