2

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

3
  • Please check my answer. Commented Nov 21, 2018 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
    Commented Nov 21, 2018 at 5:44
  • Its like a toy factory where new toys of same kind are being developed. Check this blog will help you to understand it. learningmagento.com/…
    – Avesh Naik
    Commented Sep 23, 2023 at 9:52

1 Answer 1

7

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

1
  • Its like a toy factory where new toys of same kind are being developed. Check this blog will help you to understand it. learningmagento.com/…
    – Avesh Naik
    Commented Sep 23, 2023 at 9:52

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