Magento 2 Factory Object

In this part, we will talk about Factory Object for model in Magento 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.

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


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.

For example, we will call the model to get data in Block. We will create a Topic block:


Content for this file:

namespace Mageplaza\HelloWorld\Block;
class Topic extends \Magento\Framework\View\Element\Template
	protected $_topicFactory;
	public function _construct(
		\Magento\Framework\View\Element\Template\Context $context,
		\Mageplaza\HelloWorld\Model\TopicFactory $topicFactory
		$this->_topicFactory = $topicFactory;

	public function _prepareLayout()
		$topic = $this->_topicFactory->create();
		$collection = $topic->getCollection();
		foreach($collection as $item){

As you see in this block, the TopicFactory object will be created in the _construct() function. In the _prepareLayout() function, we use $topic = $this->_topicFactory->create(); to create the model object.

Enjoyed the tutorial? Spread it to your friends!


Sam Thomas
Sam Thomas

Sam is the CEO and Founder of Mageplaza, pursuing a simple and healthy lifestyle. He is a friend, a husband, and a father to two children. As a trainer and an aspiring influencer, he is also a big fan of sports and travel. Sam is exceptionally knowledgeable about e-commerce, especially Magento and Shopify, with 10 years of experience in the field.

People also searched for

  • magento 2 factory object
  • create object in magento 2
  • magento 2 factory pattern
  • magento 2 getmodel
  • get product collection in magento 2
  • magento 2 dependency injection
  • magento 2 load model
  • magento 2 dependency injection example
  • magento 2 factory
  • magento 2 model factory
  • factory in magento 2
  • magento 2 factory class
  • magento 2 factories
  • what is factory in magento 2
  • magento factory
  • magento 2 product factory
  • type error occurred when creating object magento 2
  • magento 2 load model by multiple fields
  • type error occurred when creating object interceptor magento 2
  • magento 2 create object
  • magento 2 difference between factory and repository
  • magento 2 category factory
  • 2.2.x, 2.3.x, 2.4.x