deweller/cliopts

PHP CLI 应用程序的无废话命令行选项解析器和帮助生成器。

1.0.2 2013-01-11 14:56 UTC

This package is not auto-updated.

Last update: 2024-09-14 12:47:56 UTC


README

PHP CLI 应用程序的无废话命令行选项解析器和帮助生成器。

功能

  • 使用简单的一行代码,具有可读性强的配置格式
  • 解析 $argv 数据到与 getopt() 类似的关联数组
  • 对缺失或格式不正确的参数或选项添加错误验证
  • 生成格式优美的帮助信息
  • 支持选项(例如 -i 100)和命名参数(./script.php /tmp/myfile.txt)

使用方法

代码

在最简单的形式中,解析器可以用一行 PHP 代码使用

// specify the spec as human readable text
$values = CLIOpts\CLIOpts::run("
{self} <in_filename>
-i, --id <id> specify an id (required)
-o, --out <out_filename> output filename
-v be verbose
-h, --help show this help
");

// show the values
echo "The values you supplied are:\n";
print_r((array)$values);

CLI 输入

标志的解释有些灵活。以下几行在 cliopts 中以相同方式处理

  1. ./script.php -v -i 101 -o /tmp/myfile.txt /tmp/infile.txt

  2. ./script.php -vi 101 -o /tmp/myfile.txt /tmp/infile.txt

  3. ./script.php -v --id 101 -o /tmp/myfile.txt /tmp/infile.txt

  4. ./script.php -v --id="101" -o /tmp/myfile.txt /tmp/infile.txt

以上所有操作都会显示相同的输出

The values you supplied are:        
Array                               
(                                   
    [in_filename] => /tmp/infile.txt
    [id] => 101
    [out] => /tmp/myfile.txt
    [v] =>
)                                   

可读文本规范

让我们来看看以下代码块中的规范

$values = CLIOpts\CLIOpts::run("
  Usage: process_files.php [options] <in_file1> [<in_file2>]
  -i, --id <id> specify an id (required)
  -v be verbose
")

使用说明行

规范从使用说明行开始。此行是可选的。但如果提供了该行,以下是使用说明行是如何解释的

Usage: process_files.php [options] <in_file1> [<in_file2>]
|      |                 |         |          |
|      |                 |         |          + Optional second argument named in_file2.
|      |                 |         |
|      |                 |         + Required first argument named in_file1
|      |                 |          
|      |                 + An options placeholder.  This may be ommitted.  It must come before any arguments.
|      |
|      + An optional script name.  Omit this or use {self} to show $_SERVER['argv'][0].
|
+ The usage keyword.  This may be ommitted.

在此示例中,预期有 1 个参数,提供的值将被分配到 values 对象中的 "in_file1" 键。如果提供了可选的第 2 个参数,它将被分配到 "in_file2" 键。仅此而已。如果提供了第 3 个参数,它将不会分配到值,并且验证将失败。

选项行

下面是如何解释第一个选项行的

-i, --id <id> specify an id (required)
|   |    |    |             |
|   |    |    |             + This makes the option required when validating.
|   |    |    |
|   |    |    + Help text.  This can be any text.
|   |    |
|   |    + This specifies that the option requires a value.  Unlike arguments, this is not used for the value name.
|   |
|   + This is a long option name.  It is not required.  If specified, this is used for the value name when arguments are parsed.
|
+ This is the short option name.  It is not required.  Values can be accessed using this shortcut.