Symfony News

New in Symfony 5.1: Single command applications

Grégoire Pineau

Contributed by
Grégoire Pineau
in #34819.

The Console component is the second most popular Symfony component, with nearly 200 million downloads. It's so popular that lots of developers write all their commands with it, instead of creating traditional bash/shell commands.

For that reason, in Symfony 5.1 we've improved the way single command applications are created. This was already possible in previous Symfony versions thanks to the setDefaultCommand() method, but now it's even easier with the introduction of the new SingleCommandApplication class:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
#!/usr/bin/env php
<?php
require __DIR__.'/vendor/autoload.php';

use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

use Symfony\Component\Console\SingleCommandApplication;

(new SingleCommandApplication())
    ->setCode(function (InputInterface $input, OutputInterface $output) {

        // add here the code of your console command...

    })
    ->run();

That's all! Save this code in a file (e.g. my-command.php) and run it like any other PHP console script (php my-command.php). This new class supports every Symfony Console feature, so you can define arguments, options, the command help, etc.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
// ...
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;

use Symfony\Component\Console\SingleCommandApplication;

(new SingleCommandApplication())
    ->setName('My Super Command')
    ->setVersion('1.0.0')
    ->setHelp('This command allows you to...')
    ->addArgument('foo', InputArgument::OPTIONAL, 'The directory')
    ->addOption('bar', null, InputOption::VALUE_REQUIRED)
    ->setCode(function (InputInterface $input, OutputInterface $output) {

        // ...

    })
    ->run();

Be trained by Symfony experts - 2020-03-12 Clichy - 2020-03-16 Lille - 2020-03-16 Lyon


About us

What a Symfony developer should know about the framework: News, Jobs, Tweets, Events, Videos,...

Resources

Find us on Twitter

Find us on Facebook