Generated Classes: Extensions

In this last entry in a series looking at generated classes in Adobe Commerce, we’re examining extension classes.

Extension attributes can be created for any “extensible” entity with extension_attributes.xml:

The whole purpose of extension attributes is to “inject” new getters/setters for custom types into the explicit public API of a service contract. (They also support describing data with complex types, unlike custom attributes on EAV entities.) I could create an EAV attribute on my products called “my_attribute” and expect to fetch it with $product->getCustomAttribute("my_attribute"), but I would not expect an explicit getMyAttribute method available on the product interface with type documentation and the other benefits that come from an explicit API.

Extension attributes do provide this benefit, and another type of generated class is required to make them work. The getExtensionAttributes method of any extensible entity returns an object type, and both that object and its interface are automatically generated based on the defined extension attributes. With the above attribute definition, we should get a product extension type generated that looks like this:

The concrete class that implements the interface would similarly be generated. The result is an explicit service contract incorporated into the product entity: $product->getExtensionAttributes()->getMyAttribute().

If you’re new to extension attributes, it’s worth noting a major caveat. Declaring an attribute only does this work to extend the entity’s service contract; populating it when data is loaded is up to you! (That’s with the exception of the limited help provided by the <join> element for the context of loading a list of records.)

Chris Nanninga

Director of Training and Development at SwiftOtter -@ChrisNanninga