0

What is Factory in Magento2? Why use this. I want to know more details about Factory. When we can use Factory.

1

1 Answer 1

2

As you know in OOP, a factory method will be used to instantiate an object. In Magento 2, the Magento 2 Factory Object do the same thing. Factories are service classes that instantiate non-injectable classes, that is, models that represent a database entity. They create a layer of abstraction between the ObjectManager and business code.

The Magento\Framework\ObjectManager is the class responsible for instantiating objects in the Magento application. Magento prohibits depending on and directly using the ObjectManager in your code.

Factories are an exception to this rule because they require the ObjectManager to instantiate specific models.

Unless you require specific behavior for your factory classes, you do not need to explicitly define them because they are an automatically generated class type. When you reference a factory in a class constructor, Magento’s object manager generates the factory class if it does not exist.

Factories follow the naming convention <class-type>Factory where <class-type> is the name of the class the factory instantiates.

For example the automatically generated Magento\Cms\Model\BlockFactory class is a factory that instantiates the class Magento\Cms\Model\Block.

The Factory class name is the name of Model class and append with the Factory word. So for our example, we will have TopicFactory class. You must not create this class. Magento will create it for you. Whenever Magento’s object manager encounters a class name that ends in the word ‘Factory’, it will automatically generate the Factory class in the var/generation folder if the class does not already exist. You will see the factory class in

var/generation/<vendor_name>/<module_name>/Model/ClassFactory.php

To instantiate a model object we will use automatic constructor dependency injection to inject a factory object, then use factory object to instantiate the model object.

You can get the singleton instance of a factory for a specific model using dependency injection And Factories are smart enough to resolve dependencies and allow you to get the correct instance of an interface as defined in your module’s di.xml.

For more click here

Your Answer

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

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