Understanding Factory Classes in Magento 2
Understanding Factory Classes in Magento 2
Factory classes in Magento 2 create objects without exposing creation logic. They enable flexible object initialization through contracts (interfaces). The factory design pattern handles non-injectable objects like products and customers that have unique identities and states.
Table Of Content
What Are Factory Classes?
Factory classes create objects for all classes without using the new keyword. They instantiate non-injectable classes—models that represent database entities—and build an abstraction layer between ObjectManager and your business code.
Magento 2 auto-generates factory classes. When you need a new instance of a Data object declared in Api/Data/Data-object-name-Interface, use that interface name plus the suffix "Factory". The framework either uses the existing factory or generates one automatically.
Tip
To enhance your eCommerce store’s performance with Magento, focus on optimizing site speed by utilizing Emmo themes and extensions. These tools are designed for efficiency, ensuring your website loads quickly and provides a smooth user experience. Start leveraging Emmo's powerful solutions today to boost customer satisfaction and drive sales!
Injectable vs Non-Injectable Objects
Understanding this distinction matters for proper factory usage.
Injectable Objects These lack individual identities. Examples include EventManager and CustomerAccountManagementService. You inject them directly through constructors.
Non-Injectable Objects These have unique identities and states. All entities like Product and Customer are non-injectable because they need specific identifiers. You cannot directly depend on models like Magento\Customer\Model without specifying customer_id or customer object data.
Use factories for non-injectable objects since you don't know which specific instance you need at any given time.
How Factory Classes Work
The Factory method implementation needs only one public method—create. This method uses Object Manager to create new instances based on class name and required arguments.
Here's the basic structure:
| Component | Purpose | Notes |
|---|---|---|
| ObjectManagerInterface | Creates the actual object instance | |
| create() Method | Public method that instantiates objects | |
| Auto-generation | Framework generates factory if not explicitly defined | |
| Naming Convention | Add "Factory" suffix to class name |
Code Example
public function __construct(
\Magento\Cms\Model\BlockFactory $blockFactory
) {
$this->blockFactory = $blockFactory;
}
// Create new instance
$block = $this->blockFactory->create();
// Create with parameters
$resultItem = $this->itemFactory->create([
'title' => $item->getQueryText(),
'num_results' => $item->getNumResults()
]);
For classes requiring parameters, the auto-generated create() function accepts an array that passes to ObjectManager for target class creation.
Key Benefits
Supports Dependency Injection
Factory classes enable runtime dependency injection. This reduces coupling between classes and improves modularity. You can manage object dependencies flexibly without hardcoding class instantiation.
Ensures Consistent Object Creation
Factories create objects in controlled, predictable ways. Objects initialize with necessary data and are ready for immediate use. This consistency reduces bugs and improves application stability.
Simplifies Code
Factories resolve dependencies and deliver the correct instance of an interface as defined in your module's di.xml. Developers focus on business logic instead of object creation mechanics.
Enables Better Testing
Mock objects replace real dependencies in unit tests. Since factories handle creation and injection, you can test classes in isolation from external dependencies.
When to Use Factories
Use factories to create new entities. Repositories don't provide methods to create new entities, so factories fill this gap. Use the factory for the interface (like Magento\Catalog\Api\Data\ProductInterfaceFactory) to create the right implementation based on DI configuration.
Use Cases:
- Creating new product instances
- Instantiating customer objects
- Building order entities
- Any model representing database entities
- Objects requiring user input or database data
Avoid For:
- Service classes
- Helper classes
- Management classes
- Any injectable object without identity
Related Design Patterns
Magento 2 uses several complementary patterns:
| Pattern | Purpose |
|---|---|
| Singleton | Ensures single instance of a class |
| Dependency Injection | Injects dependencies externally |
| Observer | Subscribes to and listens for events |
| Proxy | Prevents slow chain instantiation |
| Repository | Handles data persistence operations |
Proxy classes address performance issues from constructor injection chains. When instantiating an object, all constructor dependencies also instantiate, creating slow chain reactions.
Avoiding ObjectManager Misuse
Magento prohibits depending on and directly using ObjectManager in your code. Factories are an exception because they require ObjectManager to instantiate specific models.
Using ObjectManager directly prevents the purpose of dependency injection. Always inject factory classes through constructors rather than calling ObjectManager manually.
Best Practices
- Let Magento generate factories - Unless you require specific behavior, don't explicitly define factory classes since they're automatically generated
- Add "Factory" suffix - Follow naming conventions strictly
- Use interface factories - Prefer interface factories over concrete class factories
- Inject through constructors - Never create factories inside methods
- Pass parameters via arrays - Use associative arrays for complex object creation
Performance Considerations
Factory classes add minimal overhead. The pattern has no limitations from Magento 2's perspective and follows OOP best practices and SOLID principles.
Auto-generated factories live in the generated folder. Run compilation commands after adding new factory dependencies:
php bin/magento setup:di:compile
php bin/magento cache:clean
Conclusion
Factory classes form a core component of Magento 2 architecture. They handle non-injectable object creation, support dependency injection, and maintain code quality. Understanding when and how to use factories separates proficient Magento developers from beginners.
FAQs
What are Factory classes in Magento 2?
Factory classes in Magento 2 are automatically generated classes that help create instances of models or other objects. They simplify object creation and support Magento’s dependency injection system by avoiding direct use of the new keyword.
Why does Magento 2 use Factory classes?
Magento 2 uses Factory classes to maintain flexibility and testability in its architecture. They decouple object creation from business logic, making code easier to maintain, mock, and extend without modifying core classes.
How are Factory classes generated in Magento 2?
Factories are generated automatically by Magento’s code generation system. If you have a class named Vendor\Module\Model\Example, Magento automatically creates a corresponding Vendor\Module\Model\ExampleFactory class during compilation or runtime.
How do I use a Factory class in my code?
Inject the Factory into your class constructor and use its create() method to instantiate objects. For example:
public function __construct(
\Vendor\Module\Model\ExampleFactory $exampleFactory
) {
$this->exampleFactory = $exampleFactory;
}
public function execute()
{
$example = $this->exampleFactory->create();
}
Can I pass parameters to a Factory’s create() method?
Yes. You can pass an associative array of parameters to the create() method, which are then forwarded to the class constructor:
$example = $this->exampleFactory->create(['data' => ['name' => 'Landy']]);
What’s the difference between Factories and ObjectManager?
While both can create objects, direct use of ObjectManager is discouraged. Factories provide a clean, testable, and DI-compliant way to create objects, whereas ObjectManager should only be used internally by Magento’s framework.
When should I use a Factory class?
Use a Factory when:
- You need to create objects dynamically at runtime.
- The class cannot be injected directly (e.g., dynamic model instances).
- You need to pass parameters to the object constructor during creation.
Are Factories available for all classes in Magento 2?
Factories are only generated for classes that are declared as non-abstract and located under Model, Block, or Helper directories by convention. Other classes can still have manually created factories if needed.
What are the benefits of using Factory classes?
Key benefits include:
- Cleaner, testable, and decoupled code.
- Better support for Magento’s dependency injection framework.
- Automatic code generation — no manual boilerplate needed.
- Flexibility in object instantiation and data passing.
Can I create my own custom Factory classes?
Yes, you can create a custom Factory by defining it manually or letting Magento generate it automatically. Simply type-hint the Factory in your constructor, and Magento will generate it when needed.




