Create Single Command Application in Symfony 7

Create Single Command Application in Symfony 7

Symfony provides a robust foundation for developing web applications and command line tools. When developing a command line tool, you might find it unnecessary to include multiple commands. In such instances, constantly specifying the command name can become annoying. Thankfully, it is possible to eliminate this requirement by defining a single command application. This tutorial demonstrates how to create a single command application in Symfony 7.

Symfony offers the SingleCommandApplication class that simplifies the creation of single command applications. It provides a fluent interface to configure the command. We can define the command name, description, help, version, arguments, options, etc.

Save the provided code in a file (e.g. hello.php) and run it like any other PHP console script by providing arguments and options if necessary (php hello.php John --upper).

<?php

require __DIR__.'/vendor/autoload.php';

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

(new SingleCommandApplication())
    ->setName('Hello command')
    ->setVersion('1.0.0')
    ->addArgument('name', InputArgument::REQUIRED)
    ->addOption('upper')
    ->setCode(function (InputInterface $input, OutputInterface $output): int {
        $text = 'Hello '.$input->getArgument('name');
        $output->writeln($input->getOption('upper') ? strtoupper($text) : $text);

        return Command::SUCCESS;
    })
    ->run();

Leave a Comment

Cancel reply

Your email address will not be published.