evo/cli

命令行界面

2.2.0 2024-09-11 18:13 UTC

This package is auto-updated.

Last update: 2024-09-11 18:15:00 UTC


README

命令行界面选项解析器

该库的目的是为程序设置命令行参数提供更友好的方式。

它相当直接,所以我会直接用一个示例(称为'程序')来展示。

    //command line call (typically for the help doc)
    > php {pathto}example.php -h
    
    > php {pathto}example.php -o

这是典型命令行调用的形式,这里我们假设PHP可以通过php执行。对于Windows用户,您可能需要将php.exe添加到系统环境变量中才能以这种方式调用PHP。这并不难,而且有很多教程说明如何在您的Windows版本中这样做。否则,您始终可以使用设置上的可执行文件的完整路径来调用PHP。

类参考

	//get an instance of Cli, this is a singleton class
	public static function getInstance(): self;
	//set arguments with a config array
	public function fromConfig(array $conf): self;	
	//set an argument to accept
	public function setArgument(string $shortName, ?string $longName=null, string $doc='', array $options=[]): self;
	//(changed in 2.0) get a list of the argument set with setArgument
	public function getArguments() : array;
	//(added in 2.0) get a single argument set 
	public function getArgument(string $which): array;
	//(added in 2.0) convert an arguments name to the short version ( safe for leading hypen and short names)
	public function toShortName(string $long_name): string|false;
	//(added in 2.0) convert an arguments name to the long version ( safe for leading hypens and long names)
	public function toLongName(string $short_name): string|false;
	//set the allowed request types (for overriding)
	public function setAllowedRequestTypes(int $requestType): self;	
	//set the current request types (for overriding auto detection)
	public function setCurrentRequestType(int $requestType): self;	
	//get the current request type (as of version 1.0.2)
	public function getCurrentRequestType(): int;
	//set a request (for overriding)
	public function setRequest(array $request): self;
	//(added in 2.0) get the value of an argument from the request or null to get the request as an array
	public function getRequest(?string $which=null, mixed $default=null): mixed;
	//(added in 2.2) Use this callback method as the default to throw an evo\OutOfBoundsException for an unknown request key
	public static function throwUnknownRequestKey(): callable
	//(added in 2.0) is an argument set in the request or is the request itself set
	public function issetRequest(?string $which=null): bool
	//(added in 2.1) is an argument empty in the request or is the request itself empty
	public function isEmptyRequest(?string $which=null): bool
	//get a list of the allowed options (see options)
	public function getOptions(): array;
	//get the argument help doc as text
	public function getHelpDoc(): string;
	//output the argement help doc
	public function printHelpDoc(bool $exit=true): void;
	//(added in 2.2) Stream output instead of buffering it over HTTP
	public static function streamOutput(): void

Cli类常量

通用参数定义

选项(在2.0.0版本中更改)

OPT_VALUE_EXPECTED

当此选项为true时,期望此参数有一个值

  • 如果true且参数未设置值prog.exe -a,则值是"false",请注意这与以下内容相反
  • 如果true且参数设置了值prog.exe -a=1,则值被设置
  • 如果false且参数未设置值prog.exe -a,则值是"true"
  • 如果false且参数设置了值prog.exe -a=1,则值仍然是"true",但未提供值

OPT_MUST_VALIDATE

此选项可以是布尔值或闭包(或实现Callable接口的任何类)

  • 如果设置为true,则参数在请求中始终会进行验证
  • 如果设置为false,则参数在请求中永远不会进行验证
  • 如果设置为回调,则回调负责返回true或false

OPT_MULTIPLE_EXPECTED

此选项确定一个参数是否可以有多个值 prog.exe -a=1 -a=2 -a=3

  • 如果设置为true,参数值将始终表示为数组
  • 如果设置为false,参数值永远不会表示为数组,仅设置最后一个值

基本用法

用法很简单,您需要三个主要方法,还有一些额外的辅助方法。

	//instanciate	
	$Cli = Cli::getInstance();

Cli是"单例",这意味着您只能有一个类的实例。再次调用getInstance将返回相同的实例。这是可以的,因为我们只能处理一次请求。您将使用的主要功能是$Cli->setArgument(或$Cli->fromConfig()),它定义了您将从请求中接受哪些参数。

	//instanciate	
	$Cli = Cli::getInstance();
	
	//setup a basic argument  (called -h or --help)
	$Cli->setArgument('h', 'help', 'Show this help document');

上面我们设置了一个非常基本的参数来显示参数帮助文档。

第一个参数是shortName,h在这个例子中,这主要是您引用此参数时使用的。所有传入的请求数据都将"规范化"为使用短名。任何没有对应参数的请求项都将被简单地忽略。在命令行调用中,它将被引用为-h,对于GET或POST请求,它将简单地引用为h

第二个参数是longName,help在这个例子中。任何使用可选longName的传入参数都将转换为等效的短名。在命令行调用中,它将被引用为--help,对于GET或POST请求,它将简单地引用为help

第三个参数是帮助文档。这个字符串将与所有其他参数一起编译,并通过getHelpDoc返回或由printHelpDoc输出。它还可以附加到库抛出的InvalidArgument异常。

	//instanciate	
	$Cli = Cli::getInstance();
	//setup a basic argument  (called -h or --help)
	$Cli->setArgument('h', 'help', 'Show this help document');
	//setup an argument that only accepts foo as the input
	$Cli->setArgument('f', 'foo', 'This is just foo, and must always be foo', [
		'accept' => function($shortName, $value){
			if($value == 'foo') return true;
			return false;
		}
	]);
	
	$Cli->setArgument('i', 'input', 'This is input that requires a value', [
		'requireValue' => true
	]);

第四个参数是选项数组,目前仅支持2个选项。

  • 'accept' 这是一个回调,它接收$shortName和[请求]的$value作为输入,并应返回true来接受值。如果返回false,则从请求输入中删除该参数。抛出异常由开发者负责,这可以在回调中轻松完成。可以通过添加&$value(按引用)来修改$value
  • 'requiredValue' 这是一个布尔值,使得参数的值是必需的。如果没有包括该参数的值,则会抛出evo\exception\InvalidArgument异常。这并不意味着该参数本身是必需的,只是如果该参数存在,则也包含一个可接受的值。
	//instanciate	
	$Cli = Cli::getInstance();
	$Cli->fromConfig([
		[
			'shortName' => 'h',
			'longName' => 'help',
			'doc' => 'Show this help document'
		],[
			'shortName' => 'f',
			'longName' => 'foo',
			'doc' => 'This is just foo, and must always be foo',
			'options' => [
				$Cli::OPT_MUST_VALIDATE  => function($shortName, $value){
					if($value == 'foo') return true;
					return false;
				}
			]
		],[
			'shortName' => 'i',
			'longName' => 'input',
			'doc' => 'This is input that requires a value',
			$Cli::OPT_VALUE_EXPECTED ' => [
				'requireValue' => true
			]
		]
	]);

这与前面的代码块等效,其中每个参数都是单独提供的。开发者自己决定如何保存这些参数。由于使用闭包作为'accept'选项,存在一些限制。但是,这可以作为数组保存到PHP文件中。

<?php
//example config.php
    return [['shortName' => 'h','longName' => 'help','doc' => 'Show this help document'],[...]];

然后按以下方式包含(或引入)

$config = requre 'config.php';
Cli::getInstance()->fromConfig($config);

回调的灵活性远远超过了在其他格式中保存配置的难度。

在定义了所有参数之后,您可以通过使用$Cli->getArguments()来访问它们在请求中持有的值,如下所示

	$Cli = Cli::getInstance();
	//setup a basic argument  (called -h or --help)
	$Cli->setArgument('h', 'help', 'Show this help document');
    // ... other arguments ...
    // get an array all arguments (shortName as the keys), changed in 2.0.0,
    $args = $Cli->getArguments();
    //get a single argument (using the shortName), added in 2.0.0,
    $help = $Cli->getArgument('h');
    //get a single argument (using the longName), added in 2.0.0,
    $help = $Cli->getArgument('help');
    //get the request (this will contain only valid arguments)
    $foo = $Cli->geRequest();
	//get the request value of a single argement (default null)
    $foo = $Cli->geRequest('h');
	//get the request value of a single argement (default string foo)
    $foo = $Cli->geRequest('h', 'foo');

其他方法

setAllowedRequestTypes

第一个其他方法是$Cli->setAllowedRequestTypes($requestType)。这设置允许哪些类型的请求,是Cli::REQUEST_*位运算常量之一。目前支持值为Cli::REQUEST_CLICli::REQUEST_POSTCli::REQUEST_GET。可以通过单个竖线|分隔设置多个类型,就像典型的PHP标志一样。默认为Cli::REQUEST_CLI

	$Cli = Cli::getInstance();
    //allow only $_GET
    $Cli->setAllowedRequestTypes(Cli::REQUEST_GET); 
     //allow only $_POST
    $Cli->setAllowedRequestTypes(Cli::REQUEST_POST);
     //allow only Command line (Default)
    $Cli->setAllowedRequestTypes(Cli::REQUEST_CLI);
    //allow both $_GET & $_POST
    $Cli->setAllowedRequestTypes(Cli::REQUEST_GET|Cli::REQUEST_POST);

Cli::R_ALL包含以允许所有,如果添加了额外的请求类型,此值可能会更改。例如,对于完整的REST框架。

setCurrentRequestTypes此方法提供用于覆盖自动检测。在将来实现像PUTDELETE这样的HTTP动词时,这可能有必要,因为这些HTTP动词不是所有服务器都支持。它接受单个Cli::REQUEST_*常量。目前用途有限。

setRequest此方法允许您注入一个请求数组,例如来自命令行、$_GET$_POST全局变量。这主要用于测试目的。您可以使用预制的请求数组在单元测试等中运行。

getOptions此方法返回当前支持选项的帮助文档。它主要用于方便开发者使用此库。

	print_r(Cli::getInstance()->getOptions());
    //outputs
    Array (
        [accept] => Option must be a Closure, which must return true to accept a given value for argument
        [requireValue] => Option must be a boolean value, a value is requred for this argument
    )

getHelpDoc此方法返回帮助文档作为字符串,它是由每个参数设置的$doc参数编译而成的。这主要针对命令行,开发者需要决定如何处理正常的HTTP请求。

printHelpDoc此方法与上述方法类似,但它直接输出帮助文档。您可以提供可选参数来调用exit(通常在显示帮助时使用)。默认为true,设置为false以继续脚本执行。为了灵活性,由开发者决定用于帮助的参数,但通常只是hhelp。一个示例实现

    $Cli = Cli::getInstance();
    $Cli->setArgument('h', 'help', 'Show this help document');
    //... other arguments 
    if($Cli->getArgument('h')) $Cli->printHelpDoc(); //exits

安装

您可以通过composer获取它,通过引入它。

"require" : {
    "evo/cli" : "~1.0"
}

它有2个依赖项(包含在composer.json文件中)。

"require" : {
    "evo/cli" : "~1.0"
    "evo/patterns" : "~1.0",
	"evo/exception" : "dev-master"
}

就是这样,祝您享受!