How does Magento2 generate the specific ExtensionFactory and ExtensionAttributeInterface?
First of all autogeneration is happening based on class name suffix, e.g. Factory
, ExtensionInterface
(see \Magento\Framework\Api\Code\Generator\ExtensionAttributesInterfaceGenerator::EXTENSION_INTERFACE_SUFFIX
) or Extension
(see \Magento\Framework\Api\Code\Generator\ExtensionAttributesGenerator::EXTENSION_SUFFIX
).
Proper generator is selected based on suffix here \Magento\Framework\Code\Generator::generateClass
.
Let's assume Magento mode is developer
and missing classes can be generated on fly (similar process will happen when compiler is used). When object manager tries to instantiate let's say Magento\Quote\Api\Data\CartItemExtensionFactory
and it does not exist, the following happens:
- Autoloader fails to instantiate class and initiates code generation here
\Magento\Framework\Code\Generator\Autoloader::load
- Then class suffix is determined as
Factory
(list of all declared suffixes can be found here\Magento\Framework\ObjectManager\DefinitionFactory::getCodeGenerator
) and corresponding Factory generator class (Magento\Framework\ObjectManager\Code\Generator\Factory
) is used to generate missing factory - All autogenerated classes are always based on another classes, in case of factory, source class name is calculated just by removing
Factory
suffix, it will beMagento\Quote\Api\Data\CartItemExtension
. This class does not exist and autogeneration is invoked once again by autoloader, but this time for Extension class - Now suffix is
Extension
and\Magento\Framework\Api\Code\Generator\ExtensionAttributesGenerator
will be used to generate this class - Source class for Extension class generation is calculated as
Magento\Quote\Api\Data\CartItemInterface
, it exists and Extension class is successfully generated. However, on the attempt to include Extension class file, autogeneration is triggered once again becauseMagento\Quote\Api\Data\CartItemExtension
implementsMagento\Quote\Api\Data\CartItemExtensionInterface
, which does not exist - Suffix is
ExtensionInterface
and\Magento\Framework\Api\Code\Generator\ExtensionAttributesInterfaceGenerator
will be used for generation - ExtensionInterface and Extension classes are generated based on information from
extension_attributes.xml
, accessible via\Magento\Framework\Api\ExtensionAttribute\Config
, then Factory gets generated
One important note is that there is no preference for ExtensionInterface in di.xml
because both Extension and ExtensionInterface are autogenerated. This is not a problem because ExtentionInterface is not expected to be injected via construct directly.