-
Notifications
You must be signed in to change notification settings - Fork 24
Defining Options
There are 3 basic components for parsing command-line options:
-
GetOptionKit\OptionCollection
- this is used to define option specification. -
GetOptionKit\OptionParser
- this is option parser, you pass the option specification to the parser to make it work with the given$argv
. -
GetOptionKit\OptionResult
- this is for storing parsed option result, which implements theArrayAccess
andIteratorAggregator
interface so you can manipulate the option values very easily.
GetOptionKit let you define the option specs in object oriented syntax by using GetOptionKit\OptionCollection
class:
use GetOptionKit\OptionCollection;
$specs = new OptionCollection;
$specs->add('f|foo:', 'option requires a value.' )
->isa('String');
$specs->add('b|bar+', 'option with multiple value.' )
->isa('Number');
$specs->add('z|zoo?', 'option with optional value.' )
->isa('Boolean')
;
$specs->add('o|output?', 'option with optional value.' )
->isa('File')
->defaultValue('output.txt')
;
You then pass the specs object to the parser to make everything work:
use GetOptionKit\OptionParser;
$parser = new OptionParser($specs);
$result = $parser->parse($argv);
To retrieve the option value, just use the option name to get the value from the result object:
$splFileInfo = $result->output; // defined with isa=File
$boolValue = $result->zoo; // true or false
$foo = $result->foo;
Retrieving value with short option name also works:
$f = $result->f;
To get the parsed arguments, you can do:
$args = $result->getArguments();
Spec | short name | long name | option type | accept input |
---|---|---|---|---|
f |
f | flag | -f |
|
`f | foo` | f | foo | flag |
`f | foo:` | f | foo | require a value |
`f | foo+` | f | foo | require at least one value, but accept 1+ values |
`f | foo?` | f | foo | optional value. being used with defaultValue |
To have a simple boolean option, you can use a flag option. it's pretty simple to define with a simple spec string
$options->add('d');
// even with long option name
$options->add('d|debug');
To make something like -vvv
works, you can define an option with incremental()
. a common use case would be something like this:
$options->add('v|verbose', 'verbose mode')
->isa('Number')
->incremental()
And when you pass -vvv
, you shall get $result->verbose = 3
for instance.
Related Works:
- CLIFramework: https://github.com/c9s/CLIFramework
Applications using GetOptionKit and CLIFramework:
- PHPBrew: https://github.com/phpbrew/phpbrew
- LazyRecord: https://github.com/c9s/LazyRecord
- PHPRelease: https://github.com/c9s/PHPRelease
- AssetKit: https://github.com/c9s/AssetKit
- Onion: https://github.com/c9s/Onion