asika / simple-console
一个用于编写构建脚本的文件型控制台框架。
1.0.3
2018-03-08 12:05 UTC
This package is auto-updated.
Last update: 2024-08-29 04:42:56 UTC
README
一个用于编写构建脚本的文件型控制台框架。
安装
使用composer
composer require asika/simple-console
或者下载单个文件使用: 下载链接
入门指南
使用闭包
#!/bin/sh php <?php // Include single file include_once __DIR__ . '/Console.php'; // Or use composer include_once __DIR__ . '/vendor/autolod.php'; $app = new \Asika\SimpleConsole\Console; // Use closure $app->execute(function (\Asika\SimpleConsole\Console $app) { // PHP 5.3 $app->out('Hello'); // PHP 5.4 or higher use $this $this->out('Hello'); // Return TRUE will auto convert to 0 exitcode. return true; });
或者创建你自己的类。
class Build extends \Asika\SimpleConsole\Console { protected $help = <<<HELP [Usage] php build.php <version> [Options] h | help Show help information v Show more debug information. HELP; protected function doExecute () { $this->out('Hello'); // Return TRUE will auto convert to 0 exitcode. return true; } } $app = new Build; $app->execute();
显示帮助信息
添加 -h
或 --help
来显示使用方法,你可以在 $this->help
中添加自定义使用方法,或者覆盖 $this->getHelp()
。
如果你想更改 h
和 help
选项,覆盖 $this->helpOptions = array('...')
。
处理错误
只需在 doExecute()
中抛出异常,控制台将自动捕获错误。
throw new \RuntimeException('...');
添加 -v
来显示错误时的回溯。
处理错误的参数
使用 \Asika\SimpleConsole\CommandArgsException
处理错误的参数
$arg = $this->getArgument(0); if (!$arg) { throw new \Asika\SimpleConsole\CommandArgsException('Please enter a name.'); }
控制台将自动显示帮助信息。
[Warning] Please enter a name. [Usage] console.php <name> [Options] h | help Show help info. v Show more debug information.
多个命令
使用 delegate()
将任务委托给不同的方法。
//... protected function doExecute() { return $this->delegate($this->getArgument(0)); } protected function foo() { $this->getArgument(1); // bar } protected function baz() { // ... }
现在你可以添加子命令
php console.php foo bar php console.php baz
如果你想删除委托后的第一个参数,可以参考以下代码
$this->delegate(array_shift($this->args));
现在可以在子方法中使用 getArgument(0)
并忽略第一个命令名。
这是另一种方法
$command = array_shift($this->args); $this->delegate($command, ...$this->args);
protected function foo($first, $second = null) { }
API
getArgument($order[, $default = null])
$first = $this->getArgument(0, 'default value');
setArgument($order, $$value)
$this->setArgument(1, 'value');
getOption($name: array|string[, $default = null])
获取选项 --foo
$this->getOption('foo');
获取选项 -f
或 --foo
,第一个匹配的将被返回。
$this->getOption(array('f', 'foo'));
注意:
-abc
将转换为a => 1, b => 1, c => 1
,而-vvv
将转换为v => 3
。
setOption($name, $value)
将选项添加到选项列表。 $name
也支持数组。
out($string[, $newline: bool = false])
写入到标准输出
$this->out('Hello')->out('World');
err($string[, $newline: bool = false])
写入到标准错误
$this->err('Hello')->err('World');
in($string[$default = null, $bool = false)
提问,从标准输入读取
$un = $this->in('Please enter username: ', 'default_name');
以布尔值读取,将 true 添加到第三个参数
$bool = $this->in('Are you sure? [Y/n]', [default true/false], true);
yes, y, 1, true
将转换为TRUE
no, n, 0, false
将转换为FALSE
exec($cmd)
通过 exec()
执行一个命令并返回值的一个代理。
它将在执行命令前添加一个标题 >> {你的命令}
,这样你就可以知道执行了什么。