Programmatically: Magento 2 Product Entity
Following are the various methods you can use to manage a product programmatically in Magento 2. Choose the approach that best fits for your project needs and adheres to Magento's best practices.
Here is a list of methods:- ProductRepositoryInterface
- Object Manager directly
- Data Patch Approach
- Object Manager and ProductFactory
- ProductBuilder class
ProductRepositoryInterface
Create Product Using Product Repository Interface
Create an instance of \Magento\Catalog\Api\Data\ProductInterfaceFactory.
Create an instance of \Magento\Catalog\Api\ProductRepositoryInterface.
Set the product attributes using the product object. Save the product using the save method of the product repository.
namespace CommercePeer\Products\Module;
public function __construct(
\Magento\Catalog\Api\ProductRepositoryInterface $_productRepository,
\Magento\Catalog\Api\Data\ProductInterface $product,
)
{
$this->_productRepository =$_productRepository;
$this->product=$product;
parent::__construct();
}
protected function execute()
{
$productData = [
'sku' => 'your_sku',
'name' => 'Your Product Name',
'price' => 10.99,
// Set other product attributes
];
$product = $productFactory->create(['data' => $productData]);
$productRepository->save($product);
}