1

I need to create product programmatically So either i can inject

\Magento\Catalog\Model\Product

or i can use

\Magento\Catalog\Model\ProductFactory 

from the factory i can create product model

Which one should i use.Tell me advantage and disadvantage of both

2

When to inject a Factory class

You should always inject a Factory class for any newable object. Newable objects are objects which cannot be directly instantiated, and generally require input to create, e.g. an ID, or some user data. For example, any model which will have data added, or requires data to be loaded/created is a newable object.

Non-newable (injectable) objects are classes which require no data to instantiate, and will not change over time.

Generally: if you can have more than one object of the class it's newable, if there should only ever be one object, it's injectable.

Examples of newables:

  • Data models (product, customer, etc.)
  • Collections
  • Page results

Examples of injectables:

  • Contexts
  • Repositories
  • Registry

You can read more about dependency injection in the DevDocs.

Using the Repository pattern

I would like to suggest that you use \Magento\Catalog\Api\ProductRepositoryInterface to create products programatically, as this class is marked with the @api tag.

As per item 8.5 of the Technical Guidelines given by Magento:

Only the @api code of any module can be referenced by other modules.

We should strive to only use @api code in our custom code.

To use the save method in the Product repository class, you need to pass in a \Magento\Catalog\Api\Data\ProductInterface object. To get this object, you can inject \Magento\Catalog\Api\Data\ProductInterfaceFactory and call the create method.

Below is a starting point for creating a product using the repository.

private $productRepository;
private $productInterfaceFactory;

public function __construct (
    \Magento\Catalog\Api\ProductRepositoryInterface $productRepository,
    \Magento\Catalog\Api\Data\ProductInterfaceFactory $productInterfaceFactory
) {
    $this->productRepository = $productRepository;
    $this->productInterfaceFactory = $productInterfaceFactory;
}

public function createProduct ()
{
    /** @var \Magento\Catalog\Api\Data\ProductInterface $newProduct */
    $newProduct = $this->productInterfaceFactory->create();
    $newProduct
        ->setSku('ABC')
        // ... other data
        ->setName('Abc');
    $this->productRepository->save($newProduct);
}
  • when should i use Factory class? – Krishnan Daiva Apr 5 '17 at 14:46
  • @KrishnanDaiva I've updated my answer to include information about factories – Danny Nimmo Apr 6 '17 at 0:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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