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):

MyCommand.php

<?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;
parent::__construct(self::COMMAND_NAME);
}

protected function configure(): void {

$this->setName(self::COMMAND_NAME);
$this->setDescription('This is a test command');

parent::configure();
}

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

return Command::SUCCESS;
}
}

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\CommandListInterface">
<arguments>
<argument name="commands" xsi:type="array">
<item name="mycompany_mycommandmodule" xsi:type="object">MyCompany\MyCommandModule\Console\Command\MyCommand</item>
</argument>
</arguments>
</type>
</config>

module.xml

<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<module name="MyCompany_MyCommandModule" setup_version="1.0.0"/>
</config>

registration.php

<?php

\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'MyCompany_MyCommandModule',
__DIR__
);

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:

--

--