jhonzarowny/module-seller

此包的最新版本(dev-master)没有提供许可证信息。

卖家模块示例

安装: 3

依赖关系: 0

建议者: 0

安全: 0

星标: 0

分支: 0

类型:magento2-module

dev-master 2020-07-16 01:16 UTC

This package is not auto-updated.

Last update: 2024-09-19 22:15:00 UTC


README

描述

这是一个示例 Magento 2 模块,这意味着它不适用于生产,此模块的主要目的是展示与 Magento 和 PHP 一起工作的能力。

此模块可以通过 composer 安装,这只是用于演示目的,我将在之后删除。

$ composer require jhonzarowny/module-seller:dev-master

功能

端点

  • GET /rest/V1/sellers - 将返回卖家列表
  • GET /rest/V1/sellers/:sellerId - 将返回特定卖家
  • POST /rest/V1/sellers - 将创建新的卖家

GET /rest/V1/sellers

请求

$ curl --location --request GET 'http://dev.magento23ce/rest/V1/sellers'

响应

{
    "items": [
        {
            "id": 403,
            "name": "Sample Seller 403"
        },
        {
            "id": 345,
            "name": "Sample Seller 345"
        },
        ...
    ]
}

GET /rest/V1/sellers/:sellerId

请求

$ curl --location --request GET 'http://dev.magento23ce/rest/V1/sellers/222'

响应

{
    "id": 222,
    "name": "Sample Seller 222"
}

POST /rest/V1/sellers

请求

$ curl --location --request POST 'http://dev.magento23ce/rest/V1/sellers' \
  --header 'Content-Type: application/json' \
  --data-raw '{
  	"seller": {
  		"name": "Sample Seller"
  	}
  }'

响应

{
    "id": 520,
    "name": "Sample Seller 520"
}

DTO 接口

您可以在 /Api/Data 目录中找到 Magento 模块的 DTO 接口。

对于此示例,我创建了 SellerInterface,此 DTO 将存储 Seller 信息。

DTO 实现

您可以在 /Model 目录中找到 Magento 模块的 DTO 实现。

对于此示例,我创建了 Seller

由于我们不使用 persisting 此 DTO 到 MySQL 表,Seller 类实现了 \Magento\Framework\DataObject

在第 23 行,由于我们不将其持久化到数据库,我使用 PHP rand 生成一些 Id,如果它是 null。

public function getId()
{
    if (null == $this->id) {
        $this->id = rand(10, 1000);
    }
    return $this->id;
}

服务合同接口

您可以在 服务合同 中找到我们在这里使用的 /Api 目录。

对于此示例,我创建了 SellerManagementInterface,此服务合同负责卖家的操作,如 getsavegetList

服务实现

您可以在 /Model 目录中找到 Magento 模块的服务实现。

对于此示例,我创建了 SellerManagement

在第 76 行,我创建了一个 fakeSellers 方法来模拟一些卖家数据

private function fakeSellers()
{
    $sellersDummy = [];
    for ($i=0;$i <= 100;$i++) {
        $seller = $this->sellerFactory->create();
        $seller->setName("Sample Seller {$seller->getId()}");
        $sellersDummy[] = $seller;
    }
    return $sellersDummy;
}

为了测试目的,我添加了一些 $this->logger->info("");,在实际模块中,应该在 Magento 管理面板上创建启用/禁用日志功能,以便店主或开发者可以选择在 /var/logs 目录中保存日志或不保存。

好吧,但 Magento 如何知道如何处理 GET /rest/V1/sellers

Magento 2.x 为我们提供了一个 REST api 功能的包装器,我们唯一要做的就是配置 /etc/webapi.xml 中的路由、所需的服务合同和方法。