1

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

2
  • Please check my answer. Nov 21 '18 at 5:14
  • Hi. If you want to understand M2 concepts deeply then i recommend you to read Alan Storm's M2 blog here:- alanstorm.com/category/magento-2 .Thanks.
    – Raj
    Nov 21 '18 at 5:44
4

In Magento 2, the Magento 2 Factory Object will be used to instantiate an object. The Factory class name is the name of Model class and append with the Factory word. It also dependent with ObjectManager Class.

This design pattern used to create objects for all the classes instead of using new keyword.

Newable objects are objects which cannot be directly instantiated, any model which will have data added, or requires data to be loaded/created is a newable object.

Here, example of factory instance through the constructor :

function __construct (
    \Magento\Cms\Model\BlockFactory $blockFactory
) {
    $this->blockFactory = $blockFactory;
}

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

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

create() function will get parameters and pass on to the objectManager to create the target class.

You will see the factory class in

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

OR

generated/<vendor_name>/<module_name>/Model/ClassFactory.php

For more reference : click here

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