Run Another Command From Console Command in Symfony 7

Run Another Command From Console Command in Symfony 7

Symfony provides a Console component that allows developers to create and run commands. In some scenarios, you might need to run one console command from within another command. This is handy when one command relies on another, or when you want to create a composite command to run several commands together. This tutorial shows how to run another command from console command in Symfony 7.

Let's consider a scenario where we have two commands: app:demo and app:test. The app:demo command takes a required argument, username, and an optional option, --create.

src/Command/DemoCommand.php

<?php

namespace App\Command;

use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

#[AsCommand(name: 'app:demo')]
class DemoCommand extends Command
{
    protected function configure(): void
    {
        $this
            ->addArgument('username', InputArgument::REQUIRED)
            ->addOption('create');
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $output->writeln($input->getArgument('username'));
        $output->writeln($input->getOption('create'));

        return Command::SUCCESS;
    }
}

The app:test command is designed to execute the app:demo command programmatically.

In the app:test command, we create an ArrayInput object representing the input arguments and options for the app:demo command. Then we call the doRun method that executes the app:demo command by passing the input and output. This method returns the returned code from the command.

src/Command/TestCommand.php

<?php

namespace App\Command;

use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

#[AsCommand(name: 'app:test')]
class TestCommand extends Command
{
    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $cmdInput = new ArrayInput([
            'command' => 'app:demo',
            'username' => 'john',
            '--create' => true,
        ]);

        $returnCode = $this->getApplication()?->doRun($cmdInput, $output);
        $output->writeln($returnCode);

        return Command::SUCCESS;
    }
}

Leave a Comment

Cancel reply

Your email address will not be published.