The purpose of this article is to shed some light on the flexible yet not-so-intuitive entity attribute system offered by Magento 2.
There are plenty of resources about implementing custom and extension attributes, so here we will just focus on the main differences and some details.
I would recommend referring to the official Magento documentation or, even better, watching mage2.tv for a comprehensive hands-on guide.
Quick overview of the entity attribute system
Since the early days, Magento has offered an extensible entity attribute system based on the Entity-Attribute-Value (EAV) model.
Through this system, it’s straightforward to extend a Magento entity, with some limits:
- only EAV entities can be extended with attributes; not all entities in a default Magento installation are EAV entities, just products, categories, customers, and customer addresses.
- attributes can only contain scalar values, that is,
The extension attributes system, introduced in Magento 2, overcomes the above limits, making it easy to:
- extend non-EAV entities to a condition: the entity should implement the
- use objects to have more complex types.
Unluckily, some Magento core entities don’t implement the
\Magento\Framework\Api\ExtensibleDataInterface thus they are not extensible with native extension attributes. Anyway, let’s focus on the half-full glass to explore some advantages of the extension attributes system.
What are custom attributes?
With the introduction of the extension attributes system, some new terminology comes in.
EAV attributes belong to one of the following sets:
- system attributes - created by any default Magento installation;
- custom attributes - created in the Admin Panel or through data patches.
So, simply put, a custom attribute is an EAV attribute created by someone else.
What are extension attributes?
We have already given a definition but let’s refresh it: an extension attribute is an attribute that extends a non-EAV entity.
But obviously, there is more.
First, the good news: an extension attribute allows us to overcome the limitations of scalar values. With an extension attribute, we can extend both EAV and non-EAV with complex objects.
For example, the
gift_message extension attribute added to the order (
Magento\Sales\Api\Data\OrderInterface) is of the following type:
* Constants for keys of data array. Identical to the name of the getter in snake case
const GIFT_MESSAGE_ID = 'gift_message_id';
const CUSTOMER_ID = 'customer_id';
const SENDER = 'sender';
const RECIPIENT = 'recipient';
const MESSAGE = 'message';