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?
magento2
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?
Best Answer
A 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:
You would do:
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 youruse
-statement or constructor:or:
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) orgenerated
(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.