What is Magento 2 Factory Method? Learn with a code example

What is Magento 2 Factory Method? Learn with a code example

In Magento 2, a factory method is a design pattern that can be used to create an instance of a class. The factory method pattern provides a way to create an object without specifying the exact class of object that will be created. This can be useful when the class to be instantiated is determined at runtime, rather than being hard-coded.

Here’s an example of a factory method for creating an instance of a Product class in Magento 2:

class ProductFactory
{
    /**
     * @var \Magento\Framework\ObjectManagerInterface
     */
    protected $_objectManager;

    /**
     * @param \Magento\Framework\ObjectManagerInterface $objectManager
     */
    public function __construct(\Magento\Framework\ObjectManagerInterface $objectManager)
    {
        $this->_objectManager = $objectManager;
    }

    /**
     * Create new product
     *
     * @param array $data
     * @return \Magento\Catalog\Model\Product
     */
    public function create(array $data = [])
    {
        return $this->_objectManager->create('Magento\Catalog\Model\Product', $data);
    }
}

In this example, the ProductFactory class has a single method, create(), which creates and returns a new instance of the \Magento\Catalog\Model\Product class. The method takes an optional array of data that can be used to set properties on the new product instance.

It uses ObjectManager which abstracts the actual class instantiation and makes it more flexible to be able to create different types of the same class.

The factory can be used in the following way:

$productFactory = new ProductFactory($objectManager);
$product = $productFactory->create(['sku' => 'test_sku']);

By using the factory method, you can create new instances of the Product class without needing to know the specifics of how the class is implemented. This can make your code more flexible and easier to maintain.