Add plugin to product repository

In order to add attributes, we need to use after plugin on Product Repository.
Plugin should listen next methods: save, get, getList.

We can add scalar and non-scalar extension attributes.

Scalar is simple attribute.

Non-scalar attribute can be represented by Data Object.

publicfunctionafterGet(\Magento\Catalog\Api\ProductRepositoryInterface$subject,\Magento\Catalog\Api\Data\ProductInterface$entity){$ourCustomData=$this->customDataRepository->get($entity->getId());$extensionAttributes=$entity->getExtensionAttributes();/** get current extension attributes from entity **/$extensionAttributes->setOurCustomData($ourCustomData);$entity->setExtensionAttributes($extensionAttributes);return$entity;}

It is the easiest way to add custom attributes. Because we need to know if entity
already has extension attributes.
Also we need to check whether we already has our extension attribute
.

AfterGetList is similar to afterGet.

Likewise afterSave plugin should take data from entity and do some manipulations:

publicfunctionafterSave(\Magento\Catalog\Api\ProductRepositoryInterface$subject,\Magento\Catalog\Api\Data\ProductInterface$entity){$extensionAttributes=$entity->getExtensionAttributes();/** get current extension attributes from entity **/$ourCustomData=$extensionAttributes->getOurCustomData();$this->customDataRepository->save($ourCustomData);return$entity;}

But if some entity doesn’t have implementation to fetch extension attributes, we will always retrieve null and each time when we fetch extension attributes we need to check if they are null - need to create them. To avoid such code duplication, we need to create afterGet plugin for our entity with extension attributes.

Let’s assume the product entity doesn’t have any implementation of extension attributes, so our plugin might looks like this: