2011年11月28日 星期一

PHP - GetOptionKit

The PHP built-in getopt function implements a very very simple option parser, it can not detect invalid options, invalid types, conflict options and can't parse options between arguments.

GetOptionKit is here to support more features, formats, detections and type constraints.
GitHub: https://github.com/c9s/GetOptionKit


GetOptionKit

A powerful GetOpt toolkit for PHP, which supports type constraints, flag, multiple flag, multiple values, required value checking.
GetOptionKit is based on PHP5.3, object-oriented, flexible and extendable, with fine unit testings with PHPUnit testing framework.
GetOptionKit also provides a printer class for printing well-layouted options.

Option SPEC

v|verbose   flag option (with boolean value true)
d|dir:      option require a value (MUST require)
d|dir+      option with multiple values.
d|dir?      option with optional value
dir=s       option with type constraint of string
dir=string  option with type constraint of string
dir=i       option with type constraint of integer
dir=integer option with type constraint of integer
d           single character only option
dir         long option name

Supported formats

program.php -a -b -c
program.php -abc
program.php -a -bc
with multiple values
program.php -a foo -b bar -c zoo
specify value with equal sign:
program.php -a=foo
program.php --long=foo

Synopsis

use GetOptionKit\GetOptionKit;

$getopt = new GetOptionKit;
$spec = $getopt->add( 'f|foo:' , 'option require value' );  # returns spec object.

$getopt->add( 'b|bar+' , 'option with multiple value' );
$getopt->add( 'z|zoo?' , 'option with optional value' );

$getopt->add( 'f|foo:=i' , 'option require value, with integer type' );
$getopt->add( 'f|foo:=s' , 'option require value, with string type' );

$getopt->add( 'v|verbose' , 'verbose flag' );
$getopt->add( 'd|debug'   , 'debug flag' );

$result = $opt->parse( array( 'program' , '-f' , 'foo value' , '-v' , '-d' ) );

$result = $opt->parse( $argv );

$spec = $result->verbose;
$spec = $result->debug;
$spec->value;  # get value