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:
MyCustomModule\Command\MyCustomCommand
Step 4: Register the command
In the MyCustomModule directory, create a new file etc/module.xml and add the following code:
1.0.0
9.3.0
MyCustomModule\Setup
local
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