Magento is a modular system that enables third-party developers to customize and overwrite the core parts of its framework. This flexibility, however, comes at a price. Business logic tends to leak across the layers of the Magento system, which manifests as a duplicated and inconsistent code.
Extension attributes are new in Magento 2. They are used to extend functionalities and to allow for customization of the strict Service Contracts.
What are Extension Attributes?
- Magento has many existing entities: customer, catalog_product, order, customer_address, quote, tax, promotion…
- Some Entities like the customer, catalog_product, customer_address are Entity-Attribute-Value (EAV) can add more information using the custom attribute (by program or merchant) easy to add more.
- But some entities are not EAV. In Magento 1, we need to add a new column in existing tables for new information field => hard to control with version publish after
- Extension attributes are another way to add more information for existing entities (not EAV and EAV entities)
- EAV entities can also use it in some complexity case
How to use Extension Attributes?
- Find entity data that want to add custom information. Example product: Magento\Catalog\Api\Data\ProductInterface
- Entity need to implement extension attribute: Magento\Framework\Api\ExtensibleDataInterface and must define
- Create define the module’s Extension attributes:
- Find the point need to set an extension attribute and save info to a custom field in the existing entity. Can use plugin or events for it
- The existing entity has setter and getter for extension attribute:
- Extension attribute entity automatic generated in ‘generated’ folder, after config it in a module need to remove this folder to apply the change
- Example for product entity: Magento\Catalog\Api\Data\ProductExtension
- If entity of Extension attribute have not created in generated folder function getExtensionAttributes() return null => need to create Extension attribute entity and set it setExtensionAttributes(ExtensionInterface param)