What is Factory in Magento2? Why use this. I want to know more details about Factory. When we can use Factory.
1 Answer
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