New in Symfony 5.1: Single command applications
March 12, 2020 • Published by Javier Eguiluz
Warning: This post is about an unsupported Symfony version. Some of this information may be out of date. Read the most recent Symfony Docs.
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();
Help the Symfony project!
As with any Open-Source project, contributing code or documentation is the most common way to help, but we also have a wide range of sponsoring opportunities.
Comments are closed.
To ensure that comments stay relevant, they are closed for old posts.