Tuesday, September 22, 2020
Home > Beginners of Magento 2 > What Is Factories In Magento 2?

What Is Factories In Magento 2?

Factories are service classes that instantiate non-injectable classes. That means models that represent a database entity. They create a layer of abstraction between the Object Manager and business code.

You do not need to explicitly define factory classes because they are an automatically generated class type. When you reference a factory in a class constructor, Magento 2 object manager generates the factory class if it does not exist.

Automatically generated Magento\Cms\Model\BlockFactory class is a factory that instantiates the class Magento\Cms\Model\Block.

Using factories:

You can get the singleton instance of a factory for a specific model using dependency injection.

The following example shows a class getting the BlockFactory instance through the constructor:

Calling the create() method on a factory gives you an instance of its specific class:

$block = $this->blockFactory->create();

For classes that require parameters, the automatically generated create() function accepts an array of parameters that it passes on to the ObjectManager to create the target class.

The example below shows the construction of a Magento\Search\Model\Autocomplete\Item object by passing in an array of parameters to a factory:


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 example, in the CatalogInventory module, the di.xml file contains the following entry:

It instructs Magento to use the specific Item class wherever the StockItemInterface is used. When a class in that module includes the factory StockItemInterfaceFactory as a dependency, Magento generates a factory that is capable of creating the specific Item objects.

Spread the love

Leave a Reply

Your email address will not be published.