Factory Pattern in Magento 2

In this article, we will discuss about Factory Pattern or class in Magento 2. Magento 2 Factory Pattern use for create object for all the classes. This is the OOP Concept. This same behavior of factory use in Magento 2.

When you need create object of your class, You can use factory class for create object in Magento 2 instead of using new keyword.

       

=> Factory use for create object

$customer = $customerFactory->create();


Instead of New keyword

$customer = new Customer();


Relationship between Factory and ObjectManager in Magento 2

ObjectManager is class and it's use for instantiate an object for Magento application.

We can not use objectManager directly in our code because it's prohibited or not recommended.

However, This rule is exceptional for a factory because object manager is responsible for object creation in factories.

We can easily create a factory class name using the append "Factory" word behind the Model class name.

For example : We will have Employee class so if you want to create factory class name, then just add "Factory" word behind the "Employee" class.

 EmployeeFactory is Factory class name.

You don't need to create this "EmployeeFactory" factory class. Magento  2 will create factory class for you automatically and it's auto-generated.

 When you add this factory class name in class constructor, objectManager generate this factory class in generated directory if the class does not exist.

 You can find your factory class in root generated folder.

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

Factory use in Magento 2 with Example

We will use constructor dependency injection for create factory object in Magento 2 and then use factory object to instantiate model object.

 Let's understand using below helper example.

       

<?php

 class Data extends \Magento\Framework\App\Helper\AbstractHelper

{

    /**

     * @var \Mageniks\Employee\Model\EmployeeFactory

     */

    protected $_employeeFactory;

    /**

     * @param \Magento\Framework\App\Helper\Context $context

     * @param \Mageniks\Employee\Model\EmployeeFactory $employeeFactory

     */

    public function __construct(

        \Magento\Framework\App\Helper\Context $context,

        \Mageniks\Employee\Model\EmployeeFactory $employeeFactory

    ) {

        $this->_employeeFactory = $employeeFactory;

        parent::__construct($context);

    }

    /**

     * Get Employee Collection

     */

    public function getEmployeeData()

    {

        $employeeModel = $this->_employeeFactory->create();

$employeecollection = $employeeModel->getCollection();

return $employeecollection;

    }

}


You can see above example in which EmployeeFactory added in constructor for create factory object and calling create() method for getting model object.

       

$employeeModel = $this->_employeeFactory->create();


That's it. Now i think you fully understand about factory use in Magento 2.