Create product programmatically Magento 2

In this tutorial I will explain how to create product from CLI.

Declare the module

File: app/code/PHPCodez/Product/etc/module.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/Module/etc/module.xsd">
 <module name="PHPCodez_Product" setup_version="0.0.1"/>
</config>

Register the Module

File: app/code/PHPCodez/Product/registration.php

<?php
\Magento\Framework\Component\ComponentRegistrar::register(
 \Magento\Framework\Component\ComponentRegistrar::MODULE,
 'PHPCodez_Product',
 __DIR__
);

Define command in di.xml

In di.xml file, you can use a type with name Magento\Framework\Console\CommandList to define the command option.

File: app/code/PHPCodez/First/etc/di.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
 <type name="Magento\Framework\Console\CommandList">
 <arguments>
 <argument name="commands" xsi:type="array">
 <item name="createProduct" xsi:type="object">PHPCodez\Product\Console\CreateProductCommand</item>
 </argument>
 </arguments>
 </type>
</config>

Create command class

As define in di.xml, we will create a command class:

File: app/code/PHPCodez/Product/Console/CreateProductCommand.php

<?php
namespace PHPCodez\Product\Console;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use PHPCodez\Product\Helper\Product;

class CreateProductCommand extends Command
{
 protected $productHelper;

public function __construct(Product $productHelper)
 {
 $this->productHelper = $productHelper;
 parent::__construct();
 }

protected function configure()
 {
 $this ->setName('phpcodez:product:create')
 ->setDescription('Create new products')
 ->setDefinition($this->getOptionsList());
 }

protected function execute(InputInterface $input, OutputInterface $output) {
 $output->writeln('<info>Creating Products</info>');
 $this->productHelper->setData($input);
 $this->productHelper->execute();
 $output->writeln('<info>Product is created.</info>');
 }

protected function getOptionsList()
 {
 return [
 new InputOption(product::ARG_COUNT, null, InputOption::VALUE_REQUIRED, '(Required) Count is required'),
 new InputOption(product::ARG_WEBSITE, null, InputOption::VALUE_REQUIRED, '(Required) Website ID')
 ];
 }
}

Create helper class

<?php
namespace PHPCodez\Product\Helper;

use \Magento\Framework\App\Helper\Context;
use \Magento\Store\Model\StoreManagerInterface;
use \Magento\Framework\App\State;
use \Symfony\Component\Console\Input\Input;
use \Magento\Catalog\Model\ProductFactory;

class Product extends \Magento\Framework\App\Helper\AbstractHelper
{
 const ARG_COUNT = 'count';
 const ARG_WEBSITE = 'website';
 
 protected $storeManager;
 protected $state;
 protected $ProductFactory;
 protected $data;
 
 public function __construct(
 Context $context,
 StoreManagerInterface $storeManager,
 State $state,
 ProductFactory $productFactory
 ) {
 $this->storeManager = $storeManager;
 $this->state = $state;
 $this->productFactory = $productFactory;
 
 parent::__construct($context);
 }

public function setData(Input $input)
 {
 $this->data = $input;
 return $this;
 }

public function createProduct($count){
 $website = $this->data->getOption(self::ARG_WEBSITE)?$this->data->getOption(self::ARG_WEBSITE):1;
 $product = $this->productFactory->create();
 
 $productSKU = time().$count;
 
 $product->setSku($productSKU); 
 $product->setUrlKey($productSKU); 
 $product->setName('PHPCodez Simple Product - '. date('dmy-his'));
 $product->setAttributeSetId(4); 
 $product->setStatus(1); 
 $product->setWeight(10); 
 $product->setVisibility(4); 
 $product->setTaxClassId(0); 
 $product->setTypeId('simple'); // type of product (simple/virtual/downloadable/configurable)
 $product->setPrice(100); 
 $product->setWebsiteIds(array(1)); // website ID
 $product->setCategoryIds(array(3,4)); 
 $product->setStockData(
 array(
 'use_config_manage_stock' => 0,
 'manage_stock' => 1,
 'is_in_stock' => 1,
 'qty' => 999
 )
 );
 //echo $dir = $objectManager->get('Magento\Framework\App\Filesystem\DirectoryList');
 //die; 
 $imagePath = "phpcodez.jpg"; // path of the image
 $product->addImageToMediaGallery($imagePath, array('image', 'small_image', 'thumbnail'), false, false);
 
 $product->save();
 
 return $productSKU;
 
 
 }
 
 public function execute() {
 $this->state->setAreaCode('frontend');


 $count = $this->data->getOption(self::ARG_COUNT)?$this->data->getOption(self::ARG_COUNT):1;
 $count = $count > 100? 100:$count;
 
 for($i =1;$i<=$count;$i++){
 
 $productSKU = $this->createProduct($i); 
 echo $i."- Product is created - SKU : ".$productSKU."\n";
 
 }
 }

}

Issue the following commands and you will be able to see shipping method ‘PHPCodez Easy Shipping’ on checkout page.

php bin/magento setup:upgrade
php bin/magento setup:static-content:deploy -f
php bin/magento cache:clean

Now you can create products by running the following command. Max count can be 100 at a time.

php bin/magento phpcodez:product:create --count=5

Leave a Reply

Your email address will not be published. Required fields are marked *