factory class in magento

Why to use factory class for model in Magento 2

Posted by

Factory classes act as a bridge between your application and the model classes, facilitating the instantiation of objects in a controlled manner. They provide a standardized way of creating instances, offering modularity and encapsulation benefits.

The primary reason for utilizing factory classes while loading model classes lies in managing multiple instances. If you bypass factory usage and directly employ model classes, you’d have only the initial object instance. This situation is prominent when loading models within a loop.

Example without Factory class in Magento 2 and Adobe commerce

namespace Learningmagento\Dynamicrow\Helper;

class UpdateProduct 
{
    protected $product;

    public function __construct(
      \Magento\Catalog\Model\Product $product
    )
    {
       $this->product = $product;
    }

    public function updateAttribute(array $productValues) 
    {
       foreach($productValue as $pvalue)
       {
          $product = $this->product->load($pvalue["id"]);
          $product->setData("lang", $pvalue["value"]);
          $product->save();
       }
    }
}

The provided code snippet showcases a helper class with an impactful method, updateAttribute(). This method facilitates attribute updates for a product. It efficiently takes an associative array as input, comprising product IDs and their corresponding values for modification.

During loop initiation, the method sequentially processes each product ID, loading the product object into $product. The desired value is set, and the product is saved. Consider an instance where $productValue contains an array with entries like [“id” => 5, “value” => “English”], [“id” => 6, “value” => “French”], and so forth.

Singleton design pattern

In each iteration, the process unfolds as follows: on the first iteration, product with ID 6 is updated to “English.” Subsequent iterations retain ID 6, modifying its value to “French” and eventually “Hindi.” Consequently, only the product with ID 6 receives the “Hindi” update, while others remain unchanged. This sequential update pattern resembles the singleton design pattern, offering a distinct analogy in handling updates. learn more about singleton pattern here.

Importance of Factory class

Observe, without utilizing the factory, the depicted scenario emerges. Now, what is a factory? By its name, the essence becomes apparent. It’s a site of consistent creation, akin to a doll factory. In this context, it’s a product factory. Upon appending ‘factory’ at the class conclusion, a new dimension opens — the power to generate distinct product objects. You can learn more about factory class here.

Example with Factory class

namespace Learningmagento\Dynamicrow\Helper;

class UpdateProduct 
{
    protected $productFactory;

    public function __construct(
      \Magento\Catalog\Model\ProductFactory $productFactory
    )
    {
       $this->productFactory = $productFactory;
    }

    public function updateAttribute(array $productValues) 
    {
       foreach($productValue as $pvalue)
       {
          $product = $this->productFactory->create()->load($pvalue["id"]);
          $product->setData("lang", $pvalue["value"]);
          $product->save();
       }
    }
}

Let’s revisit our example, now integrating a factory class. Note the injection of ProductFactory within the constructor. A subtle change appears in the updateAttribute() function, where the create() method from productFactory takes the spotlight.

This create() method’s role is pivotal – in each iteration, it engenders a fresh product object. This dynamic creation generates unique products per loop cycle, each subsequently loaded via load() and assigned the respective ‘lang’ attribute value. Now all products will be saved with correct values.

3 comments

  1. Hi there,I enjnoy reading through your post. I like to write a little comment tto support you.

Comments are closed.