Magento 2 — Custom Magento Command (Simple Example)

Andrew Musholt
2 min readJul 2, 2023


Magento 2 — Custom Magento Command (Simple Example)

In Magento 2, anytime you want to write custom PHP code, you must first create a “module” — which is where your PHP code will live.

For this example, our module shall be named “MyCompany\MyCommandModule” and our PHP code will be written in the MyCommand.php file.

Create this folder structure in app/code:

Copy/paste these file contents (from top to bottom):


<?php declare(strict_types=1);

namespace MyCompany\MyCommandModule\Console\Command;

use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Command\Command;
use Psr\Log\LoggerInterface;

class MyCommand extends Command
private const COMMAND_NAME = 'my:command';

private LoggerInterface $logger;

public function __construct(
LoggerInterface $logger,
$this->logger = $logger;

protected function configure(): void {

$this->setDescription('This is a test command');


protected function execute(InputInterface $input, OutputInterface $output): int
$output->writeln("Hello world CLI");
$this->logger->info("Hello world log");

return Command::SUCCESS;


<?xml version="1.0"?>
<config xmlns:xsi="" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<type name="Magento\Framework\Console\CommandListInterface">
<argument name="commands" xsi:type="array">
<item name="mycompany_mycommandmodule" xsi:type="object">MyCompany\MyCommandModule\Console\Command\MyCommand</item>


<?xml version="1.0" ?>
<config xmlns:xsi="" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<module name="MyCompany_MyCommandModule" setup_version="1.0.0"/>




Run this command to install your module (only needs to be done once):

php bin/magento setup:upgrade

Then run your custom command:

php bin/magento my:command

Your result will look like this on the command line:

As well as this log entry in your var/log/system.log: