1

I know that in Magento 2.0, there is a recommended way to access products info from another module using service contracts.

So, my first question: how can I get a product's image URL using service contracts and an API function?

Second question: I want to override product's possible "getImageUrl" function so that I can generate a custom URL (points to an external source) and return it back as Image URL. So, any other external or internal module that wants to access a product's image's URL will get my generated URL instead of Magento's default product Image URL. Should it be implemented using service contracts ? Because its the recommended way in Magento 2.0.

1 Answer 1

2

Regarding your first question, I reckon you should use Magento\Catalog\Api\ProductAttributeMediaGalleryManagementInterface

Usual process you need to first inject the class in your constructor:

protected $_productMediaGalleryInterface;

public __construct(
    ...
    \Magento\Catalog\Api\ProductAttributeMediaGalleryManagementInterface $productMediaGalleryInterface
    ...
) {
    ...
    $this->_productMediaGalleryInterface = $productMediaGalleryInterface;
    ...
}

Then in your class, based on the product sku you can retrieve the list of gallerie entries associated with the given product:

$galleryEntries = $this->_productMediaGalleryInterface->getList($sku);

However, I'm pretty sure this won't give you all the data and maybe just a list of gallery entries.

To get information about a gallery entry you can call:

$galleryEntryData = this->_productMediaGalleryInterface->get($sku, $entryId);

Regarding your second question, I should you should use plugins.

Indeed, the getImageUrl is a public method for both Magento\Catalog\Helper\Product and Magento\Catalog\Block\Product\Gallery

Thus using a plugin with after statement you should be able to change the product image URL in a clean way.

I'm not too sure how service contracts would be relevant in that case. Service contracts are relevant when you add new type of database entities via a module and you need to do simple CRUD operations.

2
  • Thanks for your great answer. I thought using service contracts we can even replace Magento's entire product functionality with something else (like connecting it to a NoSQL data structure). Is it really possible ? Commented May 26, 2016 at 11:47
  • @MichelGokan I'm not sure that's a whole another question. I suggest you mark this question as answered and open a new one ;) Commented May 26, 2016 at 11:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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