|
| 1 | +.. index:: |
| 2 | + single: Console; Single command application |
| 3 | + |
| 4 | +How to build an Application with a single Command |
| 5 | +================================================= |
| 6 | + |
| 7 | +When building a command line tool, you may not need to provide several commands. |
| 8 | +In such case, having to pass the command name each time is tedious. Fortunately, |
| 9 | +it is possible to remove this need by extending the application:: |
| 10 | + |
| 11 | + namespace Acme\Tool; |
| 12 | + |
| 13 | + use Symfony\Component\Console\Application; |
| 14 | + use Symfony\Component\Console\Input\InputInterface; |
| 15 | + |
| 16 | + class MyApplication extends Application |
| 17 | + { |
| 18 | + /** |
| 19 | + * Gets the name of the command based on input. |
| 20 | + * |
| 21 | + * @param InputInterface $input The input interface |
| 22 | + * |
| 23 | + * @return string The command name |
| 24 | + */ |
| 25 | + protected function getCommandName(InputInterface $input) |
| 26 | + { |
| 27 | + // This should return the name of your command. |
| 28 | + return 'my_command'; |
| 29 | + } |
| 30 | + |
| 31 | + /** |
| 32 | + * Gets the default commands that should always be available. |
| 33 | + * |
| 34 | + * @return array An array of default Command instances |
| 35 | + */ |
| 36 | + protected function getDefaultCommands() |
| 37 | + { |
| 38 | + // Keep the core default commands to have the HelpCommand |
| 39 | + // which is used when using the --help option |
| 40 | + $defaultCommands = parent::getDefaultCommands() |
| 41 | + |
| 42 | + $defaultCommands[] = new MyCommand(); |
| 43 | + |
| 44 | + return $defaultCommands; |
| 45 | + } |
| 46 | + } |
| 47 | + |
| 48 | +When calling your console script, the command `MyCommand` will then always |
| 49 | +be used, without having to pass its name. |
0 commit comments