|
| 1 | +.. index:: |
| 2 | + single: Console; Changing the Default Command |
| 3 | + |
| 4 | +Changing the Default Command |
| 5 | +============================ |
| 6 | + |
| 7 | +.. versionadded:: 2.5, |
| 8 | + The :method:`Symfony\\Component\\Console\\Application::setDefaultCommand` |
| 9 | + method was introduced in version 2.5. |
| 10 | + |
| 11 | +will always run the ``ListCommand`` when no command name is passed. In order to change |
| 12 | +the default command you just need to pass the command name you want to run by |
| 13 | +default to the ``setDefaultCommand`` method:: |
| 14 | + |
| 15 | + namespace Acme\Command; |
| 16 | + |
| 17 | + use Symfony\Component\Console\Command\Command; |
| 18 | + use Symfony\Component\Console\Input\InputInterface; |
| 19 | + use Symfony\Component\Console\Output\OutputInterface; |
| 20 | + |
| 21 | + class HelloWorldCommand extends Command |
| 22 | + { |
| 23 | + protected function configure() |
| 24 | + { |
| 25 | + $this->setName('hello:world') |
| 26 | + ->setDescription('Outputs \'Hello World\''); |
| 27 | + } |
| 28 | + |
| 29 | + protected function execute(InputInterface $input, OutputInterface $output) |
| 30 | + { |
| 31 | + $output->writeln('Hello World'); |
| 32 | + } |
| 33 | + } |
| 34 | + |
| 35 | +Executing the application and changing the default Command:: |
| 36 | + |
| 37 | + // application.php |
| 38 | + |
| 39 | + use Acme\Command\HelloWorldCommand; |
| 40 | + use Symfony\Component\Console\Application; |
| 41 | + |
| 42 | + $command = new HelloWorldCommand(); |
| 43 | + $application = new Application(); |
| 44 | + $application->add($command); |
| 45 | + $application->setDefaultCommand($command->getName()); |
| 46 | + $application->run(); |
| 47 | + |
| 48 | +Test the new default console command by running the following: |
| 49 | + |
| 50 | +.. code-block:: bash |
| 51 | +
|
| 52 | + $ php application.php |
| 53 | +
|
| 54 | +This will print the following to the command line: |
| 55 | + |
| 56 | +.. code-block:: text |
| 57 | +
|
| 58 | + Hello Fabien |
| 59 | +
|
| 60 | +.. tip:: |
| 61 | + |
| 62 | + This feature has a limitation: you cannot use it with any Command arguments. |
| 63 | + |
| 64 | +Learn More! |
| 65 | +----------- |
| 66 | + |
| 67 | +* :doc:`/components/console/single_command_tool` |
0 commit comments