othercode / cli
命令行界面框架。
dev-master
2018-05-11 10:08 UTC
Requires
- php: >=5.5
Requires (Dev)
This package is auto-updated.
Last update: 2024-08-29 03:42:07 UTC
README
这是一个用于构建多级链式命令的小型命令行框架。提供一个小型写入器和格式化系统,以便以自定义格式(如颜色和加粗或下划线样式)打印消息。
要求
- PHP >= 5.4.*
- PHP Readline 扩展
使用方法
首先我们需要创建一个应用程序: \App\CLIApplication.php
<?php
class CLIApplication extends \OtherCode\CLI\Command
{
/**
* Command name
*/
const NAME = 'SampleCLIApplication';
/**
* Current version
*/
const VERSION = "1.0.0";
/**
* Available commands
* @var array
*/
protected $commands = array(
'hello' => 'Sample\App\Commands\HelloCommand',
);
/**
* Display a description message
* @return string
*/
public function description()
{
return "Sample CLI Application.";
}
}
接下来创建入口点: \app.php
<?php
/**
* Include the core library
*/
require_once '../autoload.php';
/**
* Include the app files (commands and libs)
*/
require_once 'App/CLIApplication.php';
require_once 'App/Commands/HelloCommand.php';
/**
* Command line entry point
*/
$app = new Sample\App\CLIApplication();
$app->bootstrap($argv);
$app->execute();
最后,我们可以添加我们想要的任何子命令,例如
<?php
namespace Sample\App\Commands;
/**
* Class HelloCommand
* @package Sample\App
*/
class HelloCommand extends \OtherCode\CLI\Command
{
/**
* Display a description message
* @return string
*/
public function description()
{
return "Say hello world!";
}
/**
* Main code
* @param null $payload
* @return mixed|void
*/
public function run($payload = null)
{
$this->writter->info('Hello World Info');
$this->writter->input("do yo like it?", 'n', true);
}
}
我们的主要代码位于 run()
方法中,我们还可以将一些代码放入 initialize()
和 finish()
方法中。 initialize()
方法在 run()
方法之前执行,而 finish()
方法在 run()
方法之后执行。
run()
的输出传递给子命令,因此我们可以将其用作参数。最后,在 finish()
方法中,将子命令的输出再次传递给父命令。
执行命令的唯一必需方法是 run()
。
是时候运行命令了
$ php app.php
Sample CLI Application.
SampleCLIApplication v1.0.0
Options:
-h|help Show help information.
Commands:
hello Say hello world!
正在运行子命令。
$ php app.php hello
Hello World Info
do yo like it? [n]: yes