dxw/optionparser

此包已被废弃,不再维护。没有建议的替代包。
此包的最新版本(v1.0.0)没有可用的许可信息。

v1.0.0 2020-02-14 13:48 UTC

This package is auto-updated.

Last update: 2024-04-07 14:59:49 UTC


README

概述

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

此包是 Whippet 的依赖项。dxw 因上游仓库不再维护而进行了分支。

用法

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

$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 单元测试框架来测试代码。要从项目根目录运行测试,请执行以下命令

$ vendor/bin/phpunit

致谢

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

要求

OptionParser 需要 PHP 版本 5 或更高版本。

许可

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