diff --git a/components/console/index.rst b/components/console/index.rst index 9bd98fdc836..b3e3cf95d97 100644 --- a/components/console/index.rst +++ b/components/console/index.rst @@ -6,3 +6,4 @@ Console introduction usage + single_command_tool diff --git a/components/console/single_command_tool.rst b/components/console/single_command_tool.rst new file mode 100644 index 00000000000..aa1ec072315 --- /dev/null +++ b/components/console/single_command_tool.rst @@ -0,0 +1,49 @@ +.. index:: + single: Console; Single command application + +How to build an Application with a single Command +================================================= + +When building a command line tool, you may not need to provide several commands. +In such case, having to pass the command name each time is tedious. Fortunately, +it is possible to remove this need by extending the application:: + + namespace Acme\Tool; + + use Symfony\Component\Console\Application; + use Symfony\Component\Console\Input\InputInterface; + + class MyApplication extends Application + { + /** + * Gets the name of the command based on input. + * + * @param InputInterface $input The input interface + * + * @return string The command name + */ + protected function getCommandName(InputInterface $input) + { + // This should return the name of your command. + return 'my_command'; + } + + /** + * Gets the default commands that should always be available. + * + * @return array An array of default Command instances + */ + protected function getDefaultCommands() + { + // Keep the core default commands to have the HelpCommand + // which is used when using the --help option + $defaultCommands = parent::getDefaultCommands() + + $defaultCommands[] = new MyCommand(); + + return $defaultCommands; + } + } + +When calling your console script, the command `MyCommand` will then always +be used, without having to pass its name. diff --git a/components/map.rst.inc b/components/map.rst.inc index eb6fff76cd9..97cb03134c1 100644 --- a/components/map.rst.inc +++ b/components/map.rst.inc @@ -13,6 +13,7 @@ * :doc:`/components/console/introduction` * :doc:`/components/console/usage` + * :doc:`/components/console/single_command_tool` * **CSS Selector**