New in Symfony 5.1: Single command applications

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();

Comments

Great work!
Really interesting ! Thanks
Nice work! Thanks
Wow, what an awesome idea to write it that way!
Great! Will the maker bundle change to reflect this? bin/console make:command MyCommand --single?
Cool ! Thanks
Is it possible to use Doctrine or Service Container from the Single command application?
Cool!!!
Great feature ! @Serge nothing is really impossible at this level but - in my mind - the question is more : is it worth it ? Using Doctrine in this kind of "micro" application could be useful in many case. Instantiate a whole DI container with many services is more controversable. This is just a matter of thinking and building your application. But may be your question is : "How to do that ?".
Login with SymfonyConnect to post a comment