-
Notifications
You must be signed in to change notification settings - Fork 24
Option Parser
Yo-An Lin edited this page May 19, 2017
·
2 revisions
The default option parser parses the arguments passed from command-line and returns the options and normal arguments in a Result object.
To parse the arguments, you need to prepare a OptionCollection
object which contains the options you want to parse:
use GetOptionKit\OptionParser;
$opts = new OptionCollection;
$opts->add("v|verbose");
$parser = new OptionParser($opts);
echo "Enabled options: \n";
try {
$result = $parser->parse( $argv );
foreach ($result as $key => $spec) {
echo $spec->getValue() . "\n";
}
$opt = $result['f'] // return the option object.
$str = $result->f; // return the option value
$args = $result->getArguments();
var_dump($args);
} catch( Exception $e ) {
echo $e->getMessage();
}
The Result object implements ArrayAccess interface and __get
magic method.
Note that OptionParser skip the first argument by default (the first element in the argv is the program name)
When you want to get the raw option object, you use array access syntax to get the option object:
$opt = $result['verbose'] // return the option object.
When you want to get the parsed value, you can fetch the option name as the object property:
$str = $result->verbose; // return the option value
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