CommercePeer Brand Logo


Programmatically: Magento 2 Product Entity

Programmatically: How to use Magento's custom console command system for custom CLI functionality

Step 1: Create a new module

Create a new directory MyCustomModule in the app/code/local directory (or app/code/community if you want to share your module with others).

Step 2: Create the Command class

In the MyCustomModule directory, create a new file Command.php and add the following code:


	use Magento\Framework\App\Console\CommandList;
	use Magento\Framework\App\ObjectManager;
	use Magento\Framework\App\State;
	use Magento\Framework\Command\Command;
	use Magento\Framework\Stdlib\StringUtils;

	class MyCustomCommand extends Command
 {
    /**
     * @var ObjectManager
     */
    private $objectManager;

    public function __construct(State $state, ObjectManager $objectManager, StringUtils $stringUtils)
    {
        parent::__construct($state, $objectManager, $stringUtils);
        $this->objectManager = $objectManager;
    }

    public function execute($input = [])
    {
        // Your custom command logic goes here
        echo "Hello, World!"; // Just a test message
    }
  }
	

Step 3: Add the command to the console command list

In the MyCustomModule directory, create a new file etc/command/command.xml and add the following code:


	<?xml version="1.0"?>
	<config>
		<commands>
			<mycustomcommand>
				<class>MyCustomModule\Command\MyCustomCommand</class>
				<arguments>
					<argument name="input" />
				</arguments>
			</mycustomcommand>
		</commands>
	</config>
	

Step 4: Register the command

In the MyCustomModule directory, create a new file etc/module.xml and add the following code:


	<?xml version="1.0"?>
	<config>
		<modules>
			<MyCustomModule>
				<version>1.0.0</version>
				<depends>
					<Magento\Framework\App>9.3.0</Magento\Framework\App>
				</depends>
				<setup>
					<module>MyCustomModule\Setup</module>
				</setup>
				<codePool>local</codePool>
			</MyCustomModule>
		</modules>
	</config>
	

Step 5: Run the command

To run your custom command, navigate to your Magento root directory and run the following command:


		php bin/magento mycustomcommand
	

LET’S WORK TOGETHER

We love working with Small Businesses, Retailers, Manufacturers. Our team is here to Help.

→ Schedule Free Consultant Now
Copyright © 2024 CommercePeer. All Rights Reserved.