4

So I made command with two arguments:

class ServerCommand extends ContainerAwareCommand
{
    protected function configure()
    {
        $this
            ->setName('chat:server')
            ->setDescription('Start the Chat server')
            ->addArgument('host', InputArgument::REQUIRED, 'Provide a hostname')
            ->addArgument('port', InputArgument::OPTIONAL, 'Provide a port number')
        ;
    }

but server:chat command not asking me to provide arguments.

How to ask user to provide input in custom Console Command?

2 Answers 2

9

http://symfony.com/doc/current/components/console/helpers/questionhelper.html

protected function configure()
{
    $this
        ->setName('chat:server')
        ->setDescription('Start the Chat server')
        ->addArgument('host', InputArgument::REQUIRED, 'Provide a hostname')
        ->addArgument('port', InputArgument::OPTIONAL, 'Provide a port number')
    ;
}

protected function execute(InputInterface $input, OutputInterface $output)
{
    $helper = $this->getHelper('question');
    $question1 = new Question('Provide a hostname: ', 'localhost');
    $question2 = new Question('Provide a port number: ', '8080');

    $localhost = $helper->ask($input, $output, $question1);
    $port = $helper->ask($input, $output, $question2);
Sign up to request clarification or add additional context in comments.

2 Comments

Hum, yes it can helpful to read the documentation before asking questions. ^^
sure, but more helpful is to google How to ask user to provide input in custom Console Command? and be moved here
6

In addition to user6827096's answer: there's also the interact() method which can be used to pre-populate required options from interactive input using the question helper and will be called unless --no-interaction is passed to the command:

/**
 * Interacts with the user.
 *
 * This method is executed before the InputDefinition is validated.
 * This means that this is the only place where the command can
 * interactively ask for values of missing required arguments.
 *
 * @param InputInterface  $input  An InputInterface instance
 * @param OutputInterface $output An OutputInterface instance
 */
protected function interact(InputInterface $input, OutputInterface $output)
{
}

A good example of its usage in combinatoin with the question helper can be found in Sensio's Generator Bundle which is shipped with Symfony: https://github.com/sensiolabs/SensioGeneratorBundle/blob/master/Command/GenerateBundleCommand.php#L112

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.