grano22 / simplecli
以模块化和用户友好的方式轻松创建 CLI 应用
v1.0.0
2023-09-16 03:22 UTC
Requires (Dev)
- phpunit/phpunit: ^10
This package is not auto-updated.
Last update: 2024-09-29 07:16:25 UTC
README
项目详情
- 版本:v1.0.0
项目口号
“以简单和模块化的方式创建 CLI 应用 :)”
描述
此项目旨在通过添加模块(插件)来简化创建出色的 CLI 应用,以处理各种用例,例如:OutputWriter 是一个独立的组件,还有 TUI 等! :)
功能
- 将输入参数解析为顶级命令、子命令、参数和选项
- 多级命令(即将推出)
- 事件驱动方式 - 处理各种错误和其他操作
- 模块化 - 应用插件(即将推出)
示例
通用示例:
use Grano22\SimpleCli\App\Factory\SimpleCliUniversalFilterConstraint; use Grano22\SimpleCli\App\SimpleCliAppFactory; use Grano22\SimpleCli\Command\Input\SimpleCliArgument; use Grano22\SimpleCli\Command\Input\SimpleCliCommandInput; use Grano22\SimpleCli\Command\Input\SimpleCliOption; $myAwesomeCliApp = SimpleCliAppFactory::create() // Define help independent option for all commands ->withCommandsOption( commandNames: SimpleCliUniversalFilterConstraint::wildcard('*'), name: 'help', options: SimpleCliOption::OPTIONAL | SimpleCliOption::IGNORE_REST_REQUIRED | SimpleCliOption::NEGABLE ) // Add your custom unknown error handler ->setUnexpectedErrorHandler(static function(Exception $exception) { // Do something with your custom exception echo $exception->getMessage(); exit(1); }) ->withCommandsArguments( commandNames: ['greetings'], name: 'tone', options: SimpleCliArgument::REQUIRED ) ->withCommandOption( commandName: ['greetings', 'info'], name: 'verbose', options: SimpleCliOption::OPTIONAL ) // Define your command logic :) ->withCommand( name: 'greetings', executionLogic: static function(SimpleCliCommandInput $input): int { $message = "Hello world"; $tone = $input->getArguments()->getByName('tone')->getValue(); if ($tone = 'high') { $message .= '!'; } echo $message; return 0; } ) ->build() ; $myAwesomeCliApp->autoExecuteCommand();
添加事件监听器:
$myAwesomeCliApp = SimpleCliAppFactory::create() // Define your event listener for one or multiple events ->addEventsListener(static function(CommandNotFoundEvent|MissingArgumentEvent $event) { echo "Missing argument or command"; exit(1); }, [CommandNotFoundEvent::class, MissingArgumentEvent::class]) ;
添加具有别名和默认值的选项
$myAwesomeCliApp = SimpleCliAppFactory::create() ->withCommandOption( commandName: 'cmd1', name: 'optWithAliases', options: SimpleCliOption::REQUIRED, aliases: ['l', 'q'] ) ->withCommandOption( commandName: 'cmd1', name: 'optWithDefaultValue', options: SimpleCliOption::OPTIONAL, defaultValue: 'DEFAULT_VALUE' )