Skip to content
This repository was archived by the owner on Nov 19, 2024. It is now read-only.

Commit d801a5e

Browse files
authored
Merge pull request #1017 from joni-jones/patch-3
Added example how to avoid of code duplication
2 parents 071acc3 + d946b28 commit d801a5e

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

guides/v2.0/extension-dev-guide/extension_attributes/adding-attributes.md

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,62 @@ Likewise afterSave plugin should take data from entity and do some manipulations
105105
?>
106106
{% endhighlight %}
107107

108+
But if some entity doesn't have implementation to fetch extension attributes, we will always retrieve `null` and each time when we fetch extension atrributes we need to check if they are `null` - need to create them. To avoid such code duplication, we need to create `afterGet` plugin for our entity with extension attributes.
109+
110+
Let's assume the product entity doesn't have any implementation of extension attributes, so our plugin might looks like this:
111+
112+
{% highlight php startinline=1 %}
113+
114+
use Magento\Catalog\Api\Data\ProductExtensionInterface;
115+
use Magento\Catalog\Api\Data\ProductInterface;
116+
use Magento\Catalog\Api\Data\ProductExtensionFactory;
117+
118+
class ProductAttributesLoad
119+
{
120+
/**
121+
* @var ProductExtensionFactory
122+
*/
123+
private $extensionFactory;
124+
125+
/**
126+
* @param ProductExtensionFactory $extensionFactory
127+
*/
128+
public function __construct(ProductExtensionFactory $extensionFactory)
129+
{
130+
$this->extensionFactory = $extensionFactory;
131+
}
132+
133+
/**
134+
* Loads product entity extension attributes
135+
*
136+
* @param ProductInterface $entity
137+
* @param ProductExtensionInterface|null $extension
138+
* @return ProductExtensionInterface
139+
*/
140+
public function afterGetExtensionAttributes(
141+
ProductInterface $entity,
142+
ProductExtensionInterface $extension = null
143+
) {
144+
if ($extension === null) {
145+
$extension = $this->extensionFactory->create();
146+
}
147+
148+
return $extension;
149+
}
150+
}
151+
152+
{% endhighlight %}
153+
154+
And now need to bind our plugin to `ProductInterface`:
155+
156+
{% highlight xml %}
157+
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
158+
<type name="Magento\Catalog\Api\Data\ProductInterface">
159+
<plugin name="ProductExtensionAttributeOperations" type="Magento\Catalog\Plugin\ProductAttributesLoad"/>
160+
</type>
161+
</config>
162+
{% endhighlight %}
163+
108164
## Extension Attributes Configuration:
109165

110166
For scalar attributes we can use next configuration:

0 commit comments

Comments
 (0)