dxw / rubbishthorclone

该包最新版本(v1.0.2)没有可用的许可信息。

v1.0.2 2023-08-17 08:53 UTC

README

Rubbish Thor Clone 是 Ruby 编写的 CLI 应用程序流行工具集 Thor 的一个垃圾克隆。

Rubbish Thor Clone 暴露了一个具有多个子命令的可执行文件,类似于 git 或 bundler。

安装

$ cd somewhere_sensible
$ composer require dxw/RubbishThorClone dev-master

使用时,首先创建一个继承自 RubbishThorClone 的类

<?php

require __DIR__."/vendor/autoload.php";

class HelloWorld extends RubbishThorClone {

};

对于您想要定义的每个子命令,您需要添加一个定义和回调。定义在名为 commands 的方法中,回调应该是您类上的公共方法,其名称与子命令相同

class HelloWorld extends RubbishThorClone {
  public function commands() {
    $this->command('hello NAME', 'say hello to NAME');
  }

  public function hello($name) {
    echo "Hi, $name!\n";
  }
};

您还可以向子命令添加选项。要定义选项,在定义子命令时传递一个回调

public function commands() {
  $this->command('hello NAME', 'say hello to NAME', function($option_parser) {
    $option_parser->addHead("Says hello to a person.\n");
    $option_parser->addRule('s|sexy', "Congratulates NAME on their sexy face");
  });
}

添加选项后,您可以通过 $this->options 访问它们

public function hello($name) {
  echo "Hi, $name!\n";
  if(isset($this->options->sexy)) {
    echo "You have a very sexy face. Congratumalations.\n";
  }
}

Rubbish Thor Clone 使用 OptionParser 库来解析命令行,因此请查看其 API 以获取更多信息。

完成所有这些后,您只需实例化您的类并调用 start

$hello = new HelloWorld();
$hello->start($argv);

有关完整代码,请查看示例目录中的 hello_world.class.php。

Rubbish Thor Clone 的 API

RubbishThorClone::commands

您的类应实现的一个抽象函数。它预计将调用 RubbishThorClone::command 来定义所有子命令。

RubbishThorClone::command

调用此函数以定义您的子命令。它接受三个参数:$definition、$description 和(可选)$options_callback。

$definition

您的子命令的定义。由子命令名称后跟多个必选参数组成

subcommand ARG1 ARG2 [...] ARGn

必须存在于您的类中的方法与您的子命令具有相同的名称。它必须接受与子命令参数数量相等的参数。它们将按照命令行上的顺序传递到您的函数中。

您可以通过括号来指定可选参数

subcommand REQ_1 REQ_2 [OPTIONAL]

如果命令有一个可选参数,则只能有一个,并且它必须是最后一个。

您还可以通过在参数前面加上星号来绕过 RubbishThorClone 的参数解析。这在参数可以包含空格或您想自行解析事物时很有用。

subcommand *ARGUMENT

如果是一个透传参数,则命令只能有一个参数。如果您使用此记法,RubbishThorClone 将将命令行(命令名称之后)的全部内容作为单个参数传递。

$description

用于生成使用帮助的子命令的友好简短描述。

$options_callback

一个可调用的函数,它使用 OptionParser 的 API 定义您的子命令接受的选项。RubbishThorClone 有一个内置的 "帮助" 命令,其输出也来自您在此处提供的信息(使用 OptionParser::addHead 等)。

RubbishThorClone::usage

输出您已定义的子命令列表及其简短描述。

RubbishThorClone::start

接受一个参数($argv),确定如何处理它,并根据需要调用您的回调。