3

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

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!

0

All will run into Magento\Catalog\Model\ProductRepository only because we have this line

<preference for="Magento\Catalog\Api\ProductRepositoryInterface" type="Magento\Catalog\Model\ProductRepository" />

in ROOT/vendor/magento/module-catalog/etc/di.xml

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.