Skip to content
Yo-An Lin edited this page Jul 12, 2016 · 14 revisions

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 the ArrayAccess and IteratorAggregator interface so you can manipulate the option values very easily.

OptionCollection

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')
    ;

OptionParser

You then pass the specs object to the parser to make everything work:

use GetOptionKit\OptionParser;

$parser = new OptionParser($specs);
$result = $parser->parse($argv);

OptionResult

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();

Option Spec

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

Flag option

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');

Incremental Flag

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.