Generated Classes: Factories

We’re continuing our look at generated classes in Adobe Commerce, and in this segment we’re examining factories.

Unlike interceptors, factories are meant to be directly invoked in your code. As you should be familiar with, classes should not directly instantiate other classes they depend on, but should use constructor injection to receive them. Injected dependencies are typically singletons; the same instance of a class is passed to any class requesting it. Factories provide a strategy for depending on stateful classes for which your code needs the ability to create unique instances, supplying a singleton that itself is used to create those objects.

Under the hood, factories use the Object Manager for fetching a new object instance.

Writing factory classes to correspond with every stateful type would be a repetitive and tedious task, which is where code generation comes in. Any existing type can be suffixed with Factory and injected as a dependency. Magento’s DI compilation process will automatically create any such factory class that is encountered within the codebase.

It’s worth noting that factory classes can be explicitly defined when needed. The code generation process will skip generating MyVendor\MyModule\MyClassFactory if a class with that name already exists. Explicit factories can be useful when you need to factor unique logic into your object instantiation, and they’re the only truly legitimate scenario for directly invoking the Object Manager!

Chris Nanninga

Director of Training and Development at SwiftOtter -@ChrisNanninga