我不确定是什么 文档 正在说。

我知道它们用于通过以下方式添加属性(复杂或不复杂) etc/extension_attributes.xml 我设法使编译过程创建一个具有自动生成自定义方法的接口,但仅此而已。

让我们以几个接口为例: github链接1github链接2. 。如何使用扩展属性在这些接口之一中添加某些属性?我对复杂的连接不感兴趣。只需添加一个标量属性,例如类型为“attr1” string.

Data 接口是模型的入口...数据,所以我需要了解这些接口的扩展是如何工作的,以便正确使用系统。我经常得到一个 Data 接口作为参数而不是实际模型,实际上这是可以的。但我对扩展的工作原理有点困惑。

有帮助吗?

解决方案

扩展属性是扩展接口的一种方式。我们以您提供给 ProductAttributeMediaGalleryEntryInterface 的第一个链接为例。如果你查看那里的方法,你会发现它有这个方法

/**
 * Retrieve existing extension attributes object or create a new one.
 *
 * @return \Magento\Catalog\Api\Data\ProductAttributeMediaGalleryEntryExtensionInterface|null
 */
public function getExtensionAttributes();

请注意 ProductAttributeMediaGalleryEntryExtensionInterface 方法的 @return 类型 - 如果您为 ProductAttributeMediaGalleryEntryInterface 定义扩展属性,则这是一个将重新生成的接口(默认情况下,它生成为空,没有方法)。您注册的属性名称将用于创建接口方法。

假设您添加了字符串类型的 attr1。接口重新生成后您可以做的是从接口实例访问它。

$entity = $objectManager->get('..\ProductAttributeMediaGalleryEntryInterface')
$entity->getExtensionAttributes()->getAttr1();

要设置属性,您需要实例化扩展属性接口

$extension = $objectManager->get('..\ProductAttributeMediaGalleryEntryExtensionInterface')
$extension->setAttr1('value');
$entity->setExtensionAttributes($extension)

后者是可用的默认场景,它可能会根据 ExtensionInterface 和父接口的实现方式进行简化。

[更新]

自定义属性和扩展属性有不同的用途。

需要自定义属性来表示实体的 EAV 属性。大多数 EAV 属性都是动态的:它们可以在 Magento 部署后通过管理 UI 添加。这就是为什么您无法获得 EAV 属性的代码自动完成功能:你事先并不知道所有这些。

然而,作为扩展开发人员,您确实了解一些属性——您在开发时创建的属性。它可以是数据库中的新字段、相关数据库中的字段或EAV属性。您可以将它们注册为扩展属性,因为除非代码库发生更改,否则它们永远不会改变。您可以获得它们的代码自动完成功能。

其他提示

为了完成@EugeneTulika的回答,我们需要创建 /etc/extension_attributes.xml :

<?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\Catalog\Api\Data\ProductInterface">
        <attribute code="attr1" type="string" />
    </extension_attributes>
</config>

然后您可以使用 setAttr1() 方法设置新属性,如下所示:

/** @var ProductExtension $extensionAttributes */
$extensionAttributes = $product->getExtensionAttributes();
$extensionAttributes->setAttr1('super data');
$product->setExtensionAttributes($extensionAttributes);

希望这也能帮助别人:)

将要

许可以下: CC-BY-SA归因
scroll top