I’m building a custom API endpoint which produces a product data dataset for a custom front-end application. All works fine, but I want to optimise the code, because I still have multiple database requests where I guess it should be possible in one request as well.
The collection factory produces a list of products, but in order to access the Extension Attributes and Media Gallery Entries, I have to load the product via the product factory, otherwise getExtensionAttributes and getMediaGalleryEntries always return null.
I found all kinds of additional instructions for the collection but yet nothing seems to bring the desired results. What am I missing? Or is there a completely different approach for this which gets better results (better performance)?
private $productFactory;
private $productCollectionFactory;
public function __construct(
MagentoCatalogModelResourceModelProductCollectionFactory $productCollectionFactory,
MagentoCatalogModelProductFactory $productFactory
) {
$this->productCollectionFactory = $productCollectionFactory;
$this->productFactory = $productFactory;
}
public function getList()
{
$collection = $collection->addAttributeToSelect('*')->addFieldToFilter('status', ['eq' => 1])->setPageSize(10);
$result = [];
foreach ($collection->getItems() as $product) {
$result[] = $this->processProduct($product);
}
return $result;
}
private function processProduct(ProductInterface $product)
{
//build my own api response item
$responseItem = $this->responseItemFactory->create();
//retrieving sku and other basic properties works fine
$sku = $product->getSku();
//retrieving custom attributes also works fine
$customAttributes = $product->getCustomAttributes();
//these don't seem to work
$extensionAttributes = $product->getExtensionAttributes();
$mediaGalleryEntries = $product->getMediaGalleryEntries();
//this is my current workaround
$fullProduct = $this->productFactory->create()->load($product->getId());
//and fullProduct does give me ExtensionAttributes and MediaGalleryEntries
//.....
return $responseItem;
}