biurad / consolelite
这是 Symfony Console 的轻量级版本
Requires
- biurad/filephp: ^1.0
- psr/log: ^1.1
- seld/jsonlint: ^1.7
README
此库受到 Symfony Console 的强烈启发。
Console Lite - BiuradPHP 工具箱

这是 Symfony Console 的轻量级版本。@作者 Divine Niiquaye。
Console 工具允许你创建命令行命令。你的控制台命令可以用于任何重复性任务,例如stub生成器、phar编译,如cron作业、导入或其他批处理作业。
安装
只需运行此 Composer 命令
composer require biurad/consolelite
快速入门
创建控制台应用程序
首先,你需要创建一个 PHP 脚本来定义控制台应用程序
#!/usr/bin/env php <?php // application.php use BiuradPHP\Toolbox\ConsoleLite\Application; require __DIR__.'/vendor/autoload.php'; $application = new Application(); // ... register commands $application->run();
Console Lite 在构建控制台命令方面采用了完全不同的方法,与 Symfony Console 不相似,但与 Laravel Artisan 类似。这是为了使其轻量。
你可以通过两种不同的方式注册命令
-
// ... $application->register(new GenerateCommand());
-
// ... $application->command('hello', 'Enter your name to start', function () { $this->writeln('Hello World'); });
控制台命令示例
此示例用于输出一个名称而不创建类文件
#!/usr/bin/env php <?php use BiuradPHP\Toolbox\ConsoleLite\Application; require __DIR__.'/vendor/autoload.php'; // 1. Initialize app $application = new Application; // 2. Register commands $application->command('hello {name}', 'Enter your name', function($name) { $this->writeln("Hello {$name}"); }); // 3. Run app $application->run();
此示例用于输出一个名称,创建类文件
<?php use BiuradPHP\Toolbox\ConsoleLite\Command; // create a NameCommand.php class NameCommand extends Command { /** @param string The Application Name */ protected $app = 'Name Command'; /** @param string Your Set Command */ protected $signature = 'hello {name}'; /** @param string Your Command Description */ protected $description = 'Enter your name'; /** * The Command Handler * * @param string $name The Name input value. * * @return void */ public function handle($name) { return $this->writeln("Hello {$name}"); } }
然后你创建一个没有路径或文件扩展名的文件名
例如,创建一个没有文件扩展名的 console 文件
。
#!/usr/bin/env php <?php use BiuradPHP\Toolbox\ConsoleLite\Application; use NameCommand; require __DIR__.'/vendor/autoload.php'; // 1. Initialize app $application = new Application; // 2. Register commands $application->register(new NameCommand); // 3. Run app $application->run();
显示帮助
你可以通过为每个命令添加 --help
或 -h
来显示帮助。例如
php console hello --help
启用颜色
你可以通过为每个命令添加 --ansi
来强制颜色。例如
php console hello --ansi
禁用颜色
你可以通过为每个命令添加 --no-ansi
来禁用颜色。例如
php console hello --no-ansi
命令用法和选项
该命令有一个名为 signature 的强大属性,它包含所有命令、选项和参数。
基本用法很简单
-
创建一个
class
并扩展到BiuradPHP\Toolbox\ConsoleLite\Command
。 -
或使用
BiuradPHP\Toolbox\ConsoleLite\Application
的command
方法。 -
实现
properties
方法并注册选项、参数、命令并设置帮助文本-
为命令添加描述,将以下内容添加到 Application 类的受保护属性 $signature 或方法
command
。protected $description = 'Enter a description'; // add a general description.
<?php // application.php use BiuradPHP\Toolbox\ConsoleLite\Application; require __DIR__.'/vendor/autoload.php'; $app = Application; $app->command('hello', 'This is a description'/** add a general description to the second parameter. */, function () { $this->writeln('Hello World'); });
-
实现添加命令,受保护的属性 $signature 包含命令,同样适用于 Application 类的
command
方法。protected $signature = 'hello'; // add a command.
-
实现选项,将以下内容添加到受保护的属性 $signature。
protected $signature = 'hello {--option} {--anotheroption}'; // the '--' represents an option.
-
实现选项有输入,将以下内容添加到受保护的属性 $signature。
protected $signature = 'hello {--option=} {--anotheroption=}'; // the '=' represents an option has an input.
-
实现参数,将以下内容添加到受保护的属性 $signature。
protected $signature = 'hello {arguement} {anotherarguement}'; // this represents an argument.
-
为选项和参数实现描述,将以下内容添加到受保护的属性 $signature。
protected $signature = 'hello {arguement::Description} {--option::Description} {--option=::Description}'; // the '::' represents a description.
-
-
注意:这适用于 Application 类中的
command
方法。 -
实现
handle
方法并在其中执行业务逻辑。- 打开
src
文件夹中的 Command.php 文件,并查找要使用的方法。
- 打开
异常
默认情况下,CLI 类注册了两个错误或异常处理器。
-
使用 Application 异常,请使用以下示例
#!/usr/bin/env php <?php use BiuradPHP\Toolbox\ConsoleLite\Application; use BiuradPHP\Toolbox\ConsoleLite\Exception\ConsoleLiteException; use BiuradPHP\Toolbox\ConsoleLite\Exception\DeprecatedException; require __DIR__.'/vendor/autoload.php'; $application = new Application; $application->command('exception {--test} {--error} {--replace}', 'This is an exception test', function () { // This throws an application exception. if (! $this->hasOption('test')) { throw new ConsoleLiteException('Test option not allowed'); } // This throws a deprecated exception. if ($this->hasOption('error')) { throw new DeprecatedException(['--error', '--replace']); } $this->block('This is an Exception test'); }); $application->run();
彩色输出
彩色输出通过 Colors
类处理。它试图检测是否有彩色终端可用,然后才使用终端颜色。你可以始终通过将 --no-ansi
传递给脚本来抑制彩色输出。
您可以使用方便的方法 writeln()
、write()
、successBlock()
、style()
、errorBlock()
和 block()
来打印简单的彩色信息。这些方法都包含三个参数,一个用于消息,两个用于样式,包括前景色、背景色和选项。
在上文中提到的用于写入原始文本或彩色文本的方法或函数的第二个参数中,前景色、背景色或选项可以定义为字符串或数组。背景色以 'bg_' 开头,颜色直接书写。
例如,仅写入背景色:
$this->writeln('Message to output', 'bg_yellow');
例如,仅写入前景色:
$this->writeln('Message to output', 'yellow');
例如,仅写入选项:
$this->writeln('Message to output', 'italic');
例如,写入所有样式组合:
$this->writeln('Message to output', ['bg_yellow', 'green', 'bold']);
格式化器允许对整个列进行着色。要使用此机制,请将颜色数组作为第三个参数传递给其 format()
方法。请注意,您不能在第二个参数中传递彩色文本(文本长度计算和包装将失败,破坏您的文本)。
格式化器
Formatter
类允许您在多列中对文本进行对齐。它会自行尝试确定可用的终端宽度。可以通过设置 COLUMNS
环境变量来覆盖它。
格式化器通过 format()
方法使用,该方法至少需要两个数组:第一个定义列宽,第二个包含要填充到列中的文本。在每个列之间打印一个边框(默认为单个空格)。
格式化器包含用于格式化时间、内存、文件路径等的有用方法。
列宽可以以三种形式给出:
- 通过提供整数(例如
15
)提供字符固定宽度。 - 通过提供整数和百分号(例如
25%
)提供百分比。 - 使用星号(例如
*
)标记的单个流体“剩余”列。
当混合固定和百分比宽度时,百分比指的是所有固定列分配后的剩余空间。
边框的空间会自动计算。建议始终包含一些相对(百分比)或流体列,以便调整不同的终端宽度。
格式化器用于在调用脚本时使用 -h
或 --help
访问的自动帮助屏幕。
编译为 Phar
ConsoleLite 有一个功能,可以将您的 PHP 源代码编译成 Phar 文件。您不需要创建 Phar 类,ConsoleLite 会处理。
如果您在项目中将 ConsoleLite 作为 composer 依赖项安装,请执行以下操作:
php vendor/bin/clite compile --config
这将生成一个示例 clite.json 文件,如下所示:
{ "application": "ConsoleLite Configuration", "generated": "2019/06/17 03:41", "version": "1.0.0", "stuble": { "config": { "name": "ConsoleLite Stub Generator" } }, "compile": { "config": { "name": "clite.phar", "index": "docs/tests/test", "compression": 0, "signature": null }, "pack": { "autoload": "vendor/autoload.php", "bin": "docs/tests/test", "files": [ "clite.json", "composer.json" ], "directory": [ "src/", "vendor/" ], "excludes": [ "Tests/*", "!*.php" ] }, "unpack": { "extract-to": "unpack", "files": null, "overwrite": true } } }
compile
命令有两个输入类型的选项,因此有 pack 和 unpack。在 clite.json 中为它们提供不同的配置设置。
如果您已经知道 PHP 中的 Phar 类,您可以通过在 clite.json 中设置它们来完成步骤。Phar 打包或从工作目录读取目录和文件。
compile
命令之后的 pack 输入将使用 clite.json 或以下选项生成 Phar 文件。
-
--signature -> 设置 Phar 的签名。例如 openssl.key。
-
--index -> 设置 Phar 将从中加载的主文件。
-
--compression -> 设置 Phar 的压缩级别。例如 0 或 4096。
-
--directory -> 设置生成 Phar 的目录。
-
--version -> 设置项目的版本,以便保持最新。
-
--bin -> 设置要添加到编译的 Phar 文件中的 bin。
-
--files -> 添加需要的文件,例如 LICENSE 文件。
-
--excludes -> 添加从编译的 Phar 文件中排除的文件或目录。
-
--type -> 设置要生成的 phar 类型,cli 或 web。
-
--autoload -> 添加包含所有类和命名空间的文件,用于自动加载。
在 compile
命令之后,unpack 输入会将 phar 文件中包含的所有内容提取到一个目录中,从 clite.json 或使用选项读取。
-
--files -> 列出所需的文件,例如 LICENSE 文件。(可选)
-
--extract -> 设置文件和目录在 phar 中被提取到的文件夹。
-
--overwrite -> 允许覆盖之前提取的文件夹。
Stuble
Stuble 是一个使用 PHP 构建的命令行工具,用于简化与 stubs 的操作。Stuble 将收集 stub 文件中的参数并询问这些参数,因此您不需要为每个 stub 文件编写脚本。
这是一个简单的类,让您可以从模板生成一个类或 PHP 文件。这是一个抽象类,因此您不需要像 phar 一样使用它,而是使用它来创建一个 stub。
对于使用,将您的 stuble 类扩展到 StubleGenerator
。StubleGenerator 与 Laravel 的 GeneratorCommand
类似,因为该类的一部分来自 Laravel,但被简化了。请查看该类以了解更多信息。
当使用 ConsoleLite Stuble 时,您不需要输入目标路径。路径确定是从您的命名空间生成的,然后类被插入到命名空间文件夹中,从您的当前工作目录开始。
以下代码是一个实现 stuble 的示例。
<?php /* * The Biurad Toolbox ConsoleLite. * * This is an extensible library used to load classes * from namespaces and files just like composer. * * @see ReadMe.md to know more about how to load your * classes via command newLine. * * @author Divine Niiquaye <hello@biuhub.net> */ namespace BiuradPHP\Toolbox\ConsoleLite\Commands; use BiuradPHP\Toolbox\ConsoleLite\Stuble\StubGenerator; class CommandStub extends StubGenerator { /** * The console command name. * * @var string */ protected $signature = 'stuble {--command=::Enter a command name of your choice in "coomand:name" pattern.} {--force::Forces the class to be overwritten}'; /** * The console command description. * * @var string */ protected $description = 'Create a new Php File out of a stub'; /** * The type of class being generated. * * @var string */ protected $type = 'Example command'; /** * Set the namespace. * * @var string */ protected $namespace = 'App\\Console\\'; /** * Set the class. * * @var string */ protected $class = 'WorldClass'; /** * Get the stub file for the generator. * * @return string */ protected function getStub() { return __DIR__.'/../resources/stubs/example.stub'; } /** * Replace the class name for the given stub. * * @param string $stub * @param string $name * * @return string */ protected function replaceClass($stub, $name) { $stub = parent::replaceClass($stub, $name); return str_replace('generate:command', $this->hasOption('command') ?: 'command:name', $stub); } }
并且保存在 .stub
文件扩展名中的模板文件看起来像下面这样
<?php namespace GenerateNamespace; use BiuradPHP\Toolbox\ConsoleLite\Command; class GenerateClass extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'generate:command'; /** * The console command description. * * @var string */ protected $description = 'Command description'; /** * Create a new command instance. * * @return void */ public function __construct() { //code... } /** * Execute the console command. * * @return mixed */ public function handle() { //code... } }
PSR-3 记录日志
CLI 类是一个完全符合 PSR-3 的记录器(将彩色日志数据打印到 STDOUT 和 STDERR)。当您从 CLI 调用后端代码并期望 Logger 实例产生任何有意义的运行状态输出时,这非常有用。
默认情况下,记录器功能是写入 Command
类。
要使用此功能,只需从 BiuradPHP\Toolbox\ConsoleLite\PSR3
继承,而不是 BiuradPHP\Toolbox\ConsoleLite\Command
,然后传递 $this
作为记录器实例。确保您已经安装了建议的 psr/log
composer 包。