The difference in use Repository or RepositoryInterface to load model

by Key Shang   Last Updated December 07, 2017 10:09 AM

I found two ways to load model on net by service contracts in Magento 2. One is use the Repository, another is using the RepositoryInterface directly. Both work well.

What is the difference between the two ways? Which is better?

Why RepositoryInterface could be used directly and work? RepositoryInterface is just a API and no content in the method, I didn't set a di.xml for it too.

Example for using Repository

...
protected $productRepository; 
...
public function __construct(
    ...
    \Magento\Catalog\Model\ProductRepository $productRepository
    ...
) {
    ...
    $this->productRepository = $productRepository;
    ...
}

public function loadMyProduct($sku)
{
    return $this->productRepository->get($sku);
}
...

Example for using RepositoryInterface

...
protected $productRepository; 
...
public function __construct(
    ...
    \Magento\Catalog\Api\ProductRepositoryInterface $productRepository
    ...
) {
    ...
    $this->productRepository = $productRepository;
    ...
}

public function loadMyProduct($sku)
{
    return $this->productRepository->get($sku);
}
...


Answers 1


You can see in the core. The class \Magento\Catalog\Model\ProductRepository implements interface \Magento\Catalog\Api\ProductRepositoryInterface. So basically, you can use the function get($sku) of both. The difference is the ProductRepositoryInterface usually use with the API as you see. If you don't use the API, use the ProductRepository.

The ProductRepositoryInterface with no content in the method so you can find it in var/generation/Magento/Catalog/Api/ProductRepositoryInterface. Magento will auto generate the code.

There are what I find out! Hope it help!

Nero Phung
Nero Phung
December 11, 2017 04:40 AM

Related Questions




Products can't be added to cart

Updated March 05, 2017 11:09 AM