Skip to content

Magento 2.4.6. Unable to output multiple data in json format

Unfortunately, I unable to output multiple objects when I send a request to my API endpoint.

Here’s my code:

appcodeDevRestApiModelApiProductRepository.php

<?php

namespace DevRestApiModelApi;

use DevRestApiApiProductRepositoryInterface;
use DevRestApiApiDataProductInterface;
use MagentoCatalogModelResourceModelProductCollectionFactory;
use MagentoStoreModelStoreManagerInterface;
use MagentoFrameworkAppConfigScopeConfigInterface;
use MagentoFrameworkAppRequestInterface;
use MagentoFrameworkControllerResultJsonFactory;

/**
 * Class ProductRepository
 */
class ProductRepository implements ProductRepositoryInterface
{
    //A lot of valiebles


    public function __construct(
        CollectionFactory $productCollectionFactory,
        StoreManagerInterface $storeManager,
        ScopeConfigInterface $scopeConfig,
        MagentoDirectoryModelCountry $country,
        MagentoDirectoryModelCountryFactory $countryFactory
    ) {
        $this->productCollectionFactory = $productCollectionFactory;
        $this->storeManager = $storeManager;
        $this->scopeConfig = $scopeConfig;
        $this->_country = $country;
        $this->_countryFactory = $countryFactory;
    }
    public function execute(): ProductInterface
    {
        //some code
    
        if ($method == 'getProducts' && $actualToken == $token) {
            $productCollection = $this->productCollectionFactory->create();
            $productCollection->addAttributeToSelect([
                array('*')
            ]);
            $productCollection->setPageSize($count);
            $productCollection->setCurPage($offset);
    
            if ($details == 0) {
                foreach ($productCollection as $product) {
                    $countryName = $product->getAttributeText('country_of_manufacture');

                    $manufacturer = $this->getCountryCodeByFullName($countryName);
    
                    $productData = new DevRestApiModelDataProduct();
                    $productData->setSku($product->getSku());
                    $productData->setUrl($product->getUrlKey());
                    $productData->setManufacturer($manufacturer);
                    $productData->setModel($product->getModel());
                    $productData->setEan($product->getEan());
                    $productData->setPrice($product->getPrice());
                    $productData->setAvailability($product->getIsSalable() ? 'InStock' : 'OutOfStock');
                    $productData->setItemsAvailable($product->getQty());
                    $productData->setUpdateAt($product->getUpdatedAt());

                    $productsData['prods'][] = $productData;
                }
            }

            return $productData;
        } else {
            return []; 
        }
    }
    
}

My 2 interfaces:

appcodeDevRestApiApiDataMainDataInterface.php

namespace DevRestApiApiData;

use DevRestApiApiDataProductInterface;

interface MainDataInterface
{
    /**
     * @return ProductInterface
     */
    public function execute(): ProductInterface;
}

appcodeDevRestApiApiDataProductInterface.php

<?php

namespace DevRestApiApiData;

interface ProductInterface
{

    /**
     * Get SKU of the product.
     *
     * @return string|null
     */
    public function getSku(): ?string;

    /**
     * Get URL of the product.
     *
     * @return string|null
     */
    public function getUrl(): ?string;

    //and etc.
}

Product data:

appcodeDevRestApiModelDataProduct.php


namespace DevRestApiModelData;

use DevRestApiApiDataProductInterface;


class Product implements ProductInterface
{
    // private $products = [];
    private $sku;
    private $url;
    private $manufacturer;
    private $model;
    private $ean;
    private $price;
    private $availability;
    private $itemAvailable;
    private $updateAt;


    public function getSku(): ?string
    {
        return $this->sku;
    }

    public function setSku(?string $sku)
    {
        $this->sku = $sku;
    }

    public function getUrl(): ?string
    {
        return $this->url;
    }

    public function setUrl(?string $url)
    {
        $this->url = $url;
    }


    //and etc.
}

My problem:

If I output the $productData variable, I get the following data.

print_r($productsData):

Array
(
    [prods] => Array
        (
            [0] => DevRestApiModelDataProduct Object
                (
                    [sku:DevRestApiModelDataProduct:private] => 543234567
                    [url:DevRestApiModelDataProduct:private] => apple-iphone-x
                    [manufacturer:DevRestApiModelDataProduct:private] => AL
                    [model:DevRestApiModelDataProduct:private] => Apple iPhone X
                    [ean:DevRestApiModelDataProduct:private] => 0190198457141
                    [price:DevRestApiModelDataProduct:private] => 1000.000000
                    [availability:DevRestApiModelDataProduct:private] => InStock
                    [itemAvailable:DevRestApiModelDataProduct:private] => 0
                    [updateAt:DevRestApiModelDataProduct:private] => 2023-08-29 12:21:35
                )

            [1] => DevRestApiModelDataProduct Object
                (
                    [sku:DevRestApiModelDataProduct:private] => 12345678
                    [url:DevRestApiModelDataProduct:private] => samsung-galaxy-watch-4
                    [manufacturer:DevRestApiModelDataProduct:private] => LV
                    [model:DevRestApiModelDataProduct:private] => Samsung Galaxy Watch 4 Classic
                    [ean:DevRestApiModelDataProduct:private] => 0744963634260
                    [price:DevRestApiModelDataProduct:private] => 400.000000
                    [availability:DevRestApiModelDataProduct:private] => InStock
                    [itemAvailable:DevRestApiModelDataProduct:private] => 0
                    [updateAt:DevRestApiModelDataProduct:private] => 2023-10-30 18:39:02
                )

        )

)

How do I get that data back (via return)?

If I change the data in MainDataInterface like this:

interface MainDataInterface
{
    /**
     * @return ProductInterface
     */
    public function execute(): array;
}

I got this:

[
    [
        {},
        {}
    ]
]

I should get something like this:

{
   "prods": [
       {
           "sku": 543234567,
           "url": "apple-iphone-x",
           "manufacturer": "AL",
           "model": "AL",
           "ean": "0190198457141",
           "price": 1000.000000,
           "availability": "InStock",
           "items_available": 42,
           "update_at": "2023-08-29 12:21:35"
       },
       {
            "sku": "12345678",
            "url": "samsung-galaxy-watch-4",
            "manufacturer": "LV",
            "model": "Samsung Galaxy Watch 4 Classic",
            "ean": "0744963634260",
            "price": "400.000000",
            "availability": "InStock",
            "items_available": "0",
            "update_at": "2023-10-30 18:39:02"
       }
   ]
}

Please help.