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.)
- Page results
Examples of injectables:
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
As per item 8.5 of the Technical Guidelines given by Magento:
@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
Below is a starting point for creating a product using the repository.
public function __construct (
$this->productRepository = $productRepository;
$this->productInterfaceFactory = $productInterfaceFactory;
public function createProduct ()
/** @var \Magento\Catalog\Api\Data\ProductInterface $newProduct */
$newProduct = $this->productInterfaceFactory->create();
// ... other data