Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

symfony2 console arguments

I want to create a single named argument/option for symfony command. And want symfony to distinguish those 3 options:

  • my:command, which means something like my:command --arg=null
  • my:command --arg, which means my:command --arg=defalutValue
  • my:command --arg=someValue, which is fully explicit.

I.e. I want two working modes for code under that command: default one and non-default with additional argument, and that arg should have default value.

I understand, that I could create 2 args, but I'm looking for one-arg-to-rule-them-all solution.

Is it possible to accomplish that with built-in classes or should I create custom ones? If solution is only available with custom classes, please tell me, where to start (i.e. "create subclass of ..." or "install a bundle named ..."), cause I'm not familiar with Symfony2's architecture.

like image 201
kirilloid Avatar asked Apr 09 '12 13:04

kirilloid


People also ask

What is Symfony Console component?

The Console component eases the creation of beautiful and testable command line interfaces. The Console component allows you to create command-line commands. Your console commands can be used for any recurring task, such as cronjobs, imports, or other batch jobs.

How do I run console commands?

Easily open Command Prompt by running Windows Run by holding the Windows button and hitting the R button on your keyboard. You can then type "cmd" and press enter, opening Command Prompt. If you're unsure of what commands to use, you can type "Help" into Command Prompt.

What is bin console in Symfony?

The Symfony framework provides lots of commands through the bin/console script (e.g. the well-known bin/console cache:clear command). These commands are created with the Console component. You can also use it to create your own commands.


2 Answers

It is possible:

->addOption('arg', 'a', InputOption::VALUE_NONE)
  • my:command => $input->getOption('arg') //false
  • my:command --arg => $input->getOption('arg') //true
  • my:command --arg=5 => $input->getOption('arg') //5
like image 137
corvax Avatar answered Sep 19 '22 17:09

corvax


Answer by corvax is incorrect and doesn't work. As of today, you just cannot achieve this.

It is even stated in the Console documentation: Using Command Options.

See also these issues on GitHub:

  • #8135 [Console] Input options with InputOption::VALUE_OPTIONAL and InputOption::VALUE_NONE not working as expected
  • #11883 [Console] Added three state long option
  • #12769 [Console] Ability to use option default only if the option was passed
  • #12773 [Console] Add method to know parsed option
like image 34
Gras Double Avatar answered Sep 16 '22 17:09

Gras Double