fiberphp / console
⌨️ FiberPHP 控制台引擎 —— 命令注册与分发、argv 解析、ANSI 输出格式化、交互问答与表格输出。
dev-master
2026-09-30 10:38 UTC
Requires
- php: >=8.3
- ext-mbstring: *
- psr/container: ^2.0
Requires (Dev)
- phpstan/phpstan: ^2.0
- phpunit/phpunit: ^11.0
Suggests
- psr/container-implementation: 命令类经容器解析(构造注入)所需
Provides
None
Conflicts
None
Replaces
None
This package is not auto-updated.
Last update: 2026-10-11 10:17:20 UTC
README
FiberPHP 控制台引擎,提供命令注册与分发、argv 解析、ANSI 输出格式化、交互问答与表格输出。
环境要求
- PHP >= 8.3
ext-mbstring
安装
composer require fiberphp/console
定义命令
继承 FiberPHP\Console\Command,在 configure() 中声明命令名、描述、参数与选项,execute() 承载逻辑:
use FiberPHP\Console\Command;
use FiberPHP\Console\Input;
use FiberPHP\Console\Input\Argument;
use FiberPHP\Console\Input\Option;
use FiberPHP\Console\Output;
class ServeCommand extends Command
{
protected function configure(): void
{
$this->setName('serve')
->setDescription('Start the server.')
->addArgument('addr', Argument::OPTIONAL, 'Listen address', '127.0.0.1')
->addOption('port', 'p', Option::VALUE_REQUIRED, 'Listen port', '8080');
}
protected function execute(Input $input, Output $output): int
{
$output->writeln(sprintf('<info>Serving</info> %s:%s', $input->getArgument('addr'), $input->getOption('port')));
return Command::SUCCESS;
}
}
装配与运行
use FiberPHP\Console\Application;
$app = new Application('My Tool', '1.0.0');
// 可选:注入 PSR-11 容器,命令类经容器解析(支持构造注入)
$app = new Application('My Tool', '1.0.0', $container);
// 可选:宿主引导回调(加载配置、注册服务等),首次注册命令或 run() 前执行一次
$app->setBootstrapper(fn () => bootstrap());
// 注册命令:实例 / 目录扫描 / 显式类名
$app->add(new ServeCommand());
$app->installCommands(__DIR__ . '/app/Command', 'App\\Command');
$app->installCommandClasses([ServeCommand::class]);
exit($app->run());
全局选项:--help/-h(帮助)、--version/-V(版本)、--ansi / --no-ansi(ANSI 开关)。
输出与交互
Output 支持 <info> / <error> / <comment> / <question> 标签与冗赘级别;Output\Table 渲染 ASCII 表格;Output\Ask 配合 Question / ConfirmationQuestion 从 STDIN 读取回答(非交互环境直接返回默认值)。
use FiberPHP\Console\Output\Table;
use FiberPHP\Console\Output\ConfirmationQuestion;
(new Table($output))
->setHeaders(['Name', 'Version'])
->setRows([['fiberphp/console', '1.0.0']])
->render();
$confirm = $command->getHelper('question')->ask($input, $output, new ConfirmationQuestion('Continue?'));