weew / console
控制台应用程序骨架。
v1.17.1
2017-03-10 13:32 UTC
Requires
- weew/console-arguments: ^1.13
- weew/console-formatter: ^2.1
- weew/helpers-array: ^1.2
- weew/helpers-filesystem: ^1.2
- weew/helpers-string: ^1.7
- weew/json-encoder: ^1.0
Requires (Dev)
- henrikbjorn/phpspec-code-coverage: ^2.0
- phpspec/phpspec: ^2.4
- satooshi/php-coveralls: ^0.6.1
- weew/helpers-phpspec: ^1.0
README
目录
安装
composer require weew/console
简介
此包提供了一个方便的控制台应用程序骨架。从外观上看,它深受symfony控制台的影响,既有相似之处,也有不同之处。描述命令、解析控制台参数、输出样式化和着色、问题助手等,所有这些都在此包中包含。在相关项目中,你可以找到可能单独使用的组件列表。
注意:此包未在Windows上测试。非常欢迎Windows贡献。
控制台
要开始构建你的控制台应用程序,你需要首先实例化一个新的控制台。
$console = new Console();
命令
命令是你可能插入到控制台应用程序中的逻辑片段。命令可以是任何东西。没有必须满足的接口契约。这种设计选择是因为对weew/console-container-aware包的依赖注入支持。
你的命令必须具有setup
和run
方法。有关命令配置的更多信息,请参阅weew/console-arguments包。
class SampleCommand { public function setup(ICommand $command) { // describe command $command->setName('colors') ->setDescription('Shows a list of colors'); $command->argument(ArgumentType::SINGLE, 'favorite_color'); $command->argument(ArgumentType::SINGLE_OPTIONAL, '--only-light'); $command->argument(ArgumentType::SINGLE_OPTIONAL, '--only-dark'); } public function run(IInput $input, IOutput $output, IConsole $console) { // do your thang if ( ! $input->hasOption('--only-dark')) { $output->writeLine('<red>red</red>'); } if ( ! $input->hasOption('--only-light')) { $output->writeLine('<blue>blue</blue>'); } if ($input->hasArgument('favorite_color')) { $favoriteColor = $input->getArgument('favorite_color'); $output->writeLine("The best of all colors is <keyword>$favoriteColor</keyword>"); } } }
所有重要的功能都通过IInput
和IOutput
的实例提供。还有更多你可以做的事情,只需看看即可。你现在需要做的只是将你的命令注册到控制台中。
$console->addCommand(SampleCommand::class); // or $console->addCommand(new SampleCommand());
运行你的命令就像吃馅饼一样简单。
$console->parseString('colors red --only-dark'); // or $console->parseArgs(['colors', 'red', '--only-dark']; // or $console->parseArgv(['./file_name', 'colors', 'red', '--only-dark']);
你可以通过设置适当的标志来防止命令并行执行。
$command->setParallel(false);
输入
输入包含接收到的所有参数信息,并为与用户交互提供了一些API。
这就是如何检索当前命令
$input->getCommand();
你可以访问为命令匹配的参数和选项
$input->getArgument('argument'); $input->getOption('--option');
你可以使用这些方法提示用户输入
$input->readline(); $input->readChar();
输出
输出用于将信息打印到终端。它使用weew/console-formatter进行文本的样式化和格式化。
$output->writeLine('<keyword>key: </keyword> value'); $output->write('some text);
小部件
小部件是小型且可重用的类,充当一种UI元素。
表格小部件
此小部件允许你轻松打印简单的表格。
$table = new TableWidget($input, $output); $table ->setTitle('Table title') ->addRow('task1', 'x') ->addSection('Done tasks') ->addRow('task2', '✓'); $table->render();
辅助工具
有几个辅助工具可用于与用户交互。
PromptHelper
此辅助工具允许你提示用户输入不同类型的数据。
$prompt = new PromptHelper($input, $output); $response = $prompt->ask('Are you ready?'); $response = $prompt->prompt('What is your name');