Magento2 添加 Extension Attributes

分为 3 步:

1. 配置 Package/Module/etc/extension_attributes.xml :

1
2
3
4
5
6
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Api/etc/extension_attributes.xsd">
    <extension_attributes for="Magento\Sales\Api\Data\OrderInterface">
        <attribute code="test_code" type="string" />
    </extension_attributes>
</config>

2. 在 Package/Module/etc/di.xml 中给需要进行扩展的 API Interface 声明一个 plugin:
例如 给 Magento\Sales\Api\OrderRepositoryInterface 添加一个 plugin:

1
2
3
4
5
6
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
  <type name="Magento\Sales\Api\OrderRepositoryInterface">
    <plugin name="test_order_plugin" type="Package\Module\Plugin\Model\Sales\OrderPlugin" />
  </type>
</config>

3. 添加 plugin 类:
file: Package/Module/Plugin/Model/Sales/OrderPlugin;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
<?php

namespace Package\Module\Plugin\Model\Sales;

use Magento\Sales\Api\Data\OrderExtensionFactory;
use Magento\Sales\Api\OrderRepositoryInterface;
use Magento\Sales\Api\Data\OrderInterface;
use Magento\Sales\Api\Data\OrderExtension;

class OrderPlugin
{
    /**
     * @var OrderExtensionFactory
     */
    private $orderExtensionFactory;

    /**
     * @param OrderExtensionFactory $orderExtensionFactory
     */
    public function __construct(
        OrderExtensionFactory $orderExtensionFactory
    ) {
        $this->orderExtensionFactory = $orderExtensionFactory;
    }

    /**
     * Get reward points
     *
     * @param OrderRepositoryInterface $subject
     * @param OrderInterface $resultOrder
     * @return OrderInterface
     * @SuppressWarnings(PHPMD.UnusedFormalParameter)
     */
    public function afterGet(OrderRepositoryInterface $subject, OrderInterface $resultOrder)
    {
        $extensionAttributes = $resultOrder->getExtensionAttributes();

        /** @var OrderExtension $orderExtension */
        $orderExtension = $extensionAttributes
            ? $extensionAttributes
            : $this->orderExtensionFactory->create();

        $orderExtension->setTestCode($resultOrder->getTestCode());
       
        $resultOrder->setExtensionAttributes($orderExtension);

        return $resultOrder;
    }
}

刷新缓存并编译后,API 请求中就会有新增的 extension attributes.