mjackson/optionparser

该软件包最新版本(dev-master)没有可用的许可证信息。

dev-master 2015-03-17 16:57 UTC

This package is not auto-updated.

Last update: 2024-09-21 10:48:04 UTC


README

概述

OptionParser 是一个用于 PHP 命令行选项的解析器。它支持短选项和长选项,可选和/或必需参数检查,自动回调执行以及用法信息的清晰打印。

用法

首先创建一个解析器对象,然后使用它来解析您的参数。示例是最好的解释。

$parser = new OptionParser;
// add a rule that looks for the short "a" flag
$parser->addRule('a');
// add a rule that looks for the long "long-option" flag
$parser->addRule('long-option');
// add a rule that looks for the short "b" flag or long "big" flag
$parser->addRule('b|big');
// to indicate an optional parameter, use a colon after the flag name
$parser->addRule('c:');
// likewise, to indicate a required parameter use two colons
$parser->addRule('d|debug::');
// add a description for a rule that can be used later in a usage message
$parser->addRule('e', 'The description for flag e');
// or use a user-defined callback function that will be called when that
// flag is used. the function will be passed the parameter that was given
// to the flag, or true if the flag is optional and no parameter was used
$parser->addRule('error-reporting', 'set_error_reporting');

然后解析您的参数。如果需要,可以使用相同的解析器多次调用此函数来解析多组参数。注意:如果用户指定了无效的标志,此函数将抛出异常。另外,如果此处未指定任何参数,将使用全局 $argv 参数。

try {
    $parser->parse();
} catch (Exception $e) {
    die("Error parsing arguments: " . $e->getMessage());
}

可能显示用户可以使用的选项以运行您的程序的错误消息可能更有帮助

$parser->addHead("Usage: myprog [ options ]\n");

try {
    $parser->parse();
} catch (Exception $e) {
    die($parser->getUsage());
}

示例

可以使用命令行上的 PHP 解释器调用示例目录中的脚本,如下所示

$ php echo.php

还提供了 Unix 风格的可执行文件,供 *nix 用户使用

$ ./echo

测试

OptionParser 使用 PHPUnit 单元测试框架来测试代码。要从项目根目录运行测试,请执行以下命令

$ phpunit tests/OptionParser.php

致谢

OptionParser 从其他几个选项解析器中汲取灵感,包括 GNU getopt、Ruby 的 OptionParserZend_Console_Getopt

要求

OptionParser 需要 PHP 版本 5 或更高。

许可证

OptionParser 在 MIT 许可证的条款下发布。请阅读 LICENSE 文件以获取更多信息。