Magento 2 - Лучший подход для получения данных о продукте - REST API или пользовательская конечная точка?


Я хотел бы знать, какой, по вашему мнению, наилучший подход для извлечения данных о продукте из внешнего источника в Magento 2

Я попробовал два варианта, и оба работают, но я хотел бы знать, что вы считаете лучшим методом:

Способ 1 - Пользовательская конечная точка

Используя контроллер, я могу сделать запрос GET на: http://domain.com/modulename/product/index И передайте артикул в качестве параметра в запросе от внешнего источник

Затем мой контроллер вызовет мой вспомогательный класс и вернет массив данных о продукте в формате JSON:

public function execute()
{
    /**
     *  We would normally create some basic Auth check before instatiating the getProduct() method
     *  The Auth token would be stored in the admin config of the module using system.xml
     */
    return $this->resultJsonFactory->create()->setData($this->helper->getProduct());
}

И мой Помощник

  public function getProduct()
    {
        // This is just for the test I am going to load a configurable product then get the child products
        // Normally the loop would check but this is only for the test.
        $product = $this->products->get('MH01');
        // This is the parent product name and concatenated the SKU
        $productData['name'] = $product->getName() . ' ' . $product->getSku();
        // Get the child products
        $childIds = $this->configurable->getChildrenIds($product->getId());
        $childData = [];
        foreach ($childIds[0] as $childId) {
            $simple = $this->products->getById($childId);
            $childData[] = [
                'name' => $simple->getName(),
                'sku' => $simple->getSku()
            ];
        }
        return ['parent' => $productData, 'children' => $childData];
    }

Другой подход заключался бы в использовании метода веб-сервиса Magento REST API

Способ 2 - REST API

Я задаю маршрут через webapi.xml затем сделайте запрос GET на: http://domain.com/rest/V1/module-name/products /{$id}

<?xml version="1.0" ?>
<routes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Webapi:etc/webapi.xsd">
    <route method="GET" url="/V1/costa-test/products/:id">
        <service class="Costa\Test\Api\ProductsManagementInterface" method="getProducts"/>
        <resources>
            <resource ref="anonymous"/>
        </resources>
    </route>
</routes>

Класс ProductsManagementInterface примет идентификатор $ и передаст это

interface ProductsManagementInterface
{
    /**
     * GET for products api
     * @param string $id
     * @return string
     */
    public function getProducts($id);
}

Затем в моем классе управления продуктами

public function getProducts($id)
{
    // This is just for the test I am going to load a configurable product then get the child products
    // Normally the loop would check but this is only for the test.
    $product = $this->products->getById($id);
    // This is the parent product name and concatenated the SKU
    $productData['name'] = $product->getName() . ' ' . $product->getSku();
    // Get the child products
    $childIds = $this->configurable->getChildrenIds($product->getId());
    $childData = [];
    /** @var $childIds array */
    foreach ($childIds[0] as $childId) {
        $simple = $this->products->getById($childId);
        $childData[] = [
            'name' => $simple->getName(),
            'sku' => $simple->getSku(),
        ];
    }
    return ['parent' => $productData, 'children' => $childData];
}

Оба подхода работают хорошо, но что бы вы сказали, что это лучший метод?

Author: Khoa TruongDinh, 2017-11-16

1 answers

Я рекомендую использовать API Rest.

  • Если API-интерфейсы Magento по умолчанию могут соответствовать вашим требованиям, используйте их. Нам не нужно тратить деньги и время на создание нового.
  • Безопасность: API-интерфейсы в основном нуждаются в безопасности. Магенто пытался сделать это за тебя.
 2
Author: Khoa TruongDinh, 2017-11-16 14:30:17