# 让chatGPT编写Magento2插件

**URL:** https://forum.magentochina.org/t/%E8%AE%A9chatgpt%E7%BC%96%E5%86%99magento2%E6%8F%92%E4%BB%B6/1001
**Category:** Magento 2.X
**Tags:** 开发, 插件, ai
**Created:** [2023 年2 月 9 日 16:07 UTC](https://forum.magentochina.org/t/%E8%AE%A9chatgpt%E7%BC%96%E5%86%99magento2%E6%8F%92%E4%BB%B6/1001 "2023-02-09T16:07:05Z")
**Posts on this page:** 1
**Page:** 1

<div class="post-metadata">

### 作者： ![Shuai](https://forum.magentochina.org/user_avatar/forum.magentochina.org/shuai/32/3_2.png) [@Shuai](https://forum.magentochina.org/u/Shuai)
#### 发布日期： [2023 年2 月 9 日 16:07 UTC](https://forum.magentochina.org/t/%E8%AE%A9chatgpt%E7%BC%96%E5%86%99magento2%E6%8F%92%E4%BB%B6/1001/1 "2023-02-09T16:07:06Z")

</div>

最近chatGPT很火，得知它会变成，即让它写个小插件，考考它

- 需求:
  - 一个Magento2的插件,入参是SKU,输出是restful api格式的产品基本信息,包括产品名,价格,及访问地址
  - 一个完整的插件，不是代码片段。请完整编写。

### chatGPT给的回答:

好的，下面是一个完整的Magento 2插件：

1. 创建文件目录：

在您的模块目录下创建如下目录结构：

```bash
app/code/Vendor/Module/
    |- Controller/
    | |- Api/
    | | |- ProductInfo.php
    |- etc/
    | |- webapi.xml
    |- registration.php

```

1. 
  1. 编写注册文件：

在`app/code/Vendor/Module/registration.php`中，添加以下代码：

```php
<?php
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Vendor_Module',
    __DIR__
);

```

1. 编写控制器：

在`app/code/Vendor/Module/Controller/Api/ProductInfo.php`中，添加以下代码：

```php
<?php
namespace Vendor\Module\Controller\Api;

use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\Webapi\Rest\Response;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Framework\Exception\NoSuchEntityException;

class ProductInfo extends Action
{
    /**
     * @var ProductRepositoryInterface
     */
    private $productRepository;
 
    /**
     * @var Response
     */
    protected $response;
 
    /**
     * @param Context $context
     * @param ProductRepositoryInterface $productRepository
     * @param Response $response
     */
    public function __construct(
        Context $context,
        ProductRepositoryInterface $productRepository,
        Response $response
    ) {
        parent::__construct($context);
        $this->productRepository = $productRepository;
        $this->response = $response;
    }
 
    /**
     * @return \Magento\Framework\Webapi\Rest\Response
     */
    public function execute()
    {
        $sku = $this->getRequest()->getParam('sku');
        if (!$sku) {
            return $this->response->setStatusCode(400)->setContent('Invalid request, missing parameter `sku`.');
        }
 
        try {
            $product = $this->productRepository->get($sku);
            $result = [
                'name' => $product->getName(),
                'price' => $product->getPrice(),
                'url' => $product->getProductUrl(),
            ];
            return $this->response->setData($result)->setStatusCode(200);
} catch (NoSuchEntityException $e) {
return $this->response->setStatusCode(404)->setContent('Product not found.');
}
}
}

```

1. 编写路由：

在`app/code/Vendor/Module/etc/webapi.xml`中，添加以下代码：

```xml
<?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 url="/V1/product/info" method="GET">
        <service class="Vendor\Module\Api\ProductInfoManagementInterface" method="getProductInfo"/>
        <resources>
            <resource ref="anonymous"/>
        </resources>
    </route>
</routes>

```

最后，在Magento 2的命令行界面中运行以下命令，以安装并启用您的模块：

```bash
php bin/magento module:enable Vendor_Module
php bin/magento setup:upgrade
php bin/magento cache:flush

```

现在，您可以通过以下URL访问该API：

> [http://your-magento-instance.com/rest/V1/product/info?sku=product\_sku](http://your-magento-instance.com/rest/V1/product/info?sku=product_sku)

替换`product_sku` 为要查询的产品的SKU。

### 总结

代码能力还可以，虽然没有直接运行，但是感觉稍微改改就能直接用.
