danbettles/command-line-tools

仅包含一些基本类,可以更轻松地编写命令行脚本。当使用类似Symfony Console这样的工具过于强大时,可以使用这个库。

v1.0.0-beta.1 2022-11-17 13:57 UTC

This package is auto-updated.

Last update: 2024-09-26 01:25:30 UTC


README

跳转到安装说明.

该库仅包含一些基本类,可以更轻松地编写命令行PHP脚本。它提供了运行外部程序的帮助器和向输出发送格式化消息的方法。当使用类似 Symfony Console 这样的工具过于强大时,可以使用这个库。

主要组件类包括 OutputMessageFormatterHost

Output

在屏幕上显示消息;它提供输出不同风格消息的方法。

例如

(new Output())->writeLine('A plain-looking message followed by a newline.');

(new Output())->danger('A brightly-coloured message about something that just went wrong, followed by a newline.');

运行 php tests/show_output_formats.php 查看Output能做什么。

MessageFormatter

提供用于创建格式化消息的流畅接口。 它使用类似CSS的方法,尽可能使用CSS命名约定,使Web开发者更容易、更直观地完成任务。

例如,以下两个调用都会在亮红色的背景上创建相同的加粗白色消息。

$formattedMessage = (new MessageFormatter())
    ->fontWeight('bold')
    ->backgroundColor('maroon')
    ->format('A brightly-coloured message about something that just went wrong')
;

$formattedMessage = MessageFormatter::createFromStyleDeclarations([
    'font-weight' => 'bold',
    'background-color' => 'maroon',
])->format('A brightly-coloured message about something that just went wrong');

当从样式声明数组创建格式化器时,您可以使用CSS风格的连字符命名或驼峰命名。

MessageFormatter 将自动为前景使用对比色,如果只设置了背景色。

请参阅下文的样式参考部分,了解您可以做什么。

样式参考

运行 php tests/show_styles.php 查看每个样式设置的效果,并确定您的终端是否支持该样式。

Host

提供了一个有用的 passthru() 包装器,它除了输出其执行命令的输出外,还会在默认情况下在出现错误时抛出异常。

例如

$output = new Output();
$host = new Host($output);

// Throws an exception if something goes wrong.
$host->passthru('ls -al --color=always');

// Will not throw an exception if something goes wrong: instead, will display a formatted error message and return a value indicating the problem that occurred.
$resultCode = $host->passthru('ls -al --color=always', false);

安装

除了PHP 7+之外没有其他依赖项。

使用Composer运行 composer require danbettles/command-line-tools 进行安装。

参考