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);
}
...


Related Questions




Products can't be added to cart

Updated March 05, 2017 11:09 AM