In Magento 2, When to use Factory and Model?
What is the difference between them?
Can we use our Custom Module's model as Factory?
Magento Stack Exchange is a question and answer site for users of the Magento e-Commerce platform. It only takes a minute to sign up.
Sign up to join this communityA Factory creates a Model. It's a design pattern (separate from Magento 2).
Typically, when you need to create a new instance of your class/entity, you would want a factory to create that. So instead of:
$product = new Product();
You would do:
$product = $productFactory->create();
Having a factory instead of using the new
-keyword has multiple benefits. For example:
But you don't want to manually create all those factories by yourself (because it's boring and repeating most of the times). That's why Magento 2 uses code generation to create these factory classes for you. Just add Factory
after the class name in your use
-statement or constructor:
use Vendor\Module\Model\ExampleFactory;
or:
public function __construct(
Vendor\Module\Model\ExampleFactory $exampleFactory
) {
$this->exampleFactory = $exampleFactory;
}
Don't worry about warnings that the class does not exist by your IDE; Magento will create them for you. After a reload the class will be generated (in the var/generation
(2.1) or generated
(2.2) folder).
The only time when you want to create your own factory is if you want to apply some custom logic upon instantiating your object. But often that's not required.