enygma/cmd

简单的命令行选项解析器

0.4 2016-06-09 13:18 UTC

This package is auto-updated.

Last update: 2024-09-15 10:53:52 UTC


README

Travis-CI Build Status

此库提供了一些在命令行上工作的便捷工具

  • 一个简单的接口,用于将 $_SERVER['argv'] 输入值解析为键/值对(Command
  • 一个输出处理库,使得格式化输出变得简单(Output

安装

使用 Composer

composer require enygma/cmd

示例用法

<?php

require_once 'vendor/autoload.php';
use Cmd\Command;

$cmd = new Command();
$args = $cmd->execute($_SERVER['argv']);

echo 'RESULT: '.var_export($args, true)."\n";
?>

命令:示例

对于命令行的调用

php test.php plain-arg --foo --bar=baz --funny="spam=eggs" --also-funny=spam=eggs 'plain arg 2' -abc -k=value "plain arg 3" --s="original" --s='overwrite' --s

结果将是

Array
(
    [0] => plain-arg
    [foo] => 1
    [bar] => baz
    [funny] => spam=eggs
    [also-funny] => spam=eggs
    [1] => plain arg 2
    [abc] => 1
    [k] => value
    [2] => plain arg 3
    [s] => 1
)

那些是普通参数(如 plain-argplain arg 3)的选项将仅以数字索引添加到结果中。其他选项将被分配为结果数组中的键/值对。对于已设置(如 -abc--foo)但没有值的选项,其值将被设置为布尔值 true

命令:必选和默认值

您还可以为命令行选项设置默认值和必选参数。使用 execute 方法调用的可选第二个参数来定义这些

<?php

require_once 'vendor/autoload.php';
use Cmd\Command;

$cmd = new Command();
$config = [
  'default' => ['foo' => true],
  'required' => ['bar']
];

$args = $cmd->execute($_SERVER['argv'], $config);

echo 'RESULT: '.var_export($args, true)."\n";

?>

default 值被定义为参数名称 => 默认值的数组。required 设置仅表示为一个选项名称的数组。

输出:示例

<?php

require_once 'vendor/autoload.php';
use Cmd\Output;

$out = new Output();
$out->success('Success message goes here!');
?>

默认方法

  • 成功
  • 警告
  • 信息
  • 错误

如果您想要可重复使用的格式,也可以定义自定义类型

<?php
require_once 'vendor/autoload.php';
use Cmd\Output;

$out = new Output();
$out->addType('custom1', 'white', 'blue');

$out->custom1('A custom message');
?>

第一个参数是自定义格式的名称。第二个和第三个是前景色和背景色。