dface/tito

这是一个小类,可以帮助您为应用程序构建轻量级的命令行工具

2.0.0 2020-08-02 17:03 UTC

This package is auto-updated.

Last update: 2024-09-21 15:30:13 UTC


README

小型工具

辅助类,用于创建CLI工具以调用应用程序服务。

php tito.php <service_name> <method_name> <param1> <param2> ...

它从一个容器中获取一个<service>,调用一个方法并输出结果。要定位服务,需要一个服务定位器回调。

设置

composer require dface/tito

用法

让我们创建一个示例小型工具来展示这个概念。

创建一个名为tito.php的文件,并包含以下内容。(您可以选择任何其他名称)

<?php
// please modify this to conform with your class-loading strategy:
include_once 'vendor/autoload.php';

// example service class
class Test {

	function process($val){
		return $val;
	}

	function info(){
		return $_SERVER['argv'];
	}

}

// kinda container
$container = [
	'service1' => new Test('service1'),
	'service2' => new Test('service2'),
];

// Initialize tito - pass in description and service-locator callback:
$tito = new \dface\tito\Tito(
	'X-system command line tool.',
	function ($service_name) use ($container){
		return $container[$service_name];
	}
);

// ask tito to make the rest
$tito->call();

从命令行执行脚本。现在不要传递任何参数。

php tito.php

您将看到信息屏幕。

X-system command line tool.

Makes a service method call and outputs a result.

Usage: php tito.php [options] <call>

A <call> can be in the default form:
  <service> <method> [<arg1> <arg2> ...]

or as JSON array, if -j specified:
  '["<service>", "<method>" [,<args array>]]'

A result is either:
  [true, <returned value>] - for successful calls
or
  [false, <exception type>, <message>] - for failed ones.

Results are displayed in JSON format unless -p|-y|-l specified.

Options:
  -j   <call> passed in JSON format
  -p   output a result with print_r instead of JSON
  -y   output a result as YAML instead of JSON
  -l   output a result as list of lines (values only)
  -q   quite mode - skip result status 'true' for successful call
  -s   silent mode - no output for successful calls
  -v   verbose mode - don't suppress service stdout, don't suppress error_reporting
  -t   add a stacktrace to failed results
  -i   input encoding (utf-8 assumed by default)
  -b   service internal encoding (utf-8 assumed by default)
  -o   output encoding (input encoding assumed by default)
  -d   max recursion depth for encoding conversion (default 512)
  -x   eval specified code before making service call
  -e   set exit code to '1' for failed calls


现在尝试使用它

php tito.php service1 process hi
[true,"hi"]

它输出一个包含两个元素的JSON格式数组 - 状态和返回值。

状态true表示调用成功,返回值位于数组的第二个元素。

状态false表示由于某些原因调用失败。使用false您还会收到异常类型和消息

php tito.php asd process hi
[false,"dface\\tito\\TitoException","No such service 'asd'"]