7

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?

0

1 Answer 1

19

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:

$product = new Product();

You would do:

$product = $productFactory->create();

Having a factory instead of using the new-keyword has multiple benefits. For example:

  • It allows for dependency injection when it comes to creating new instances (which is great for unit testing for example).
  • It provides a hook into the constructing-process of your instances.
  • It's more SOLID.

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.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.