-
Notifications
You must be signed in to change notification settings - Fork 48
like sf command
Inhere edited this page Jan 15, 2019
·
2 revisions
支持像symfony console一样配置命令,严谨的设置每个参数和选项信息。
- 选项支持设置
OPT_BOOLEAN
OPT_REQUIRED
OPT_OPTIONAL
OPT_IS_ARRAY
,以及短选项命 - 参数支持
ARG_REQUIRED
ARG_OPTIONAL
ARG_IS_ARRAY
- 设置为 REQUIRED 后,应用运行时会严格检查是否有对应的值传入
- 如果将参数 设置为 ARRAY,那它必须是最后一个参数
<?php
namespace Inhere\Console\Examples\Command;
use Inhere\Console\Command;
use Inhere\Console\IO\Input;
use Inhere\Console\IO\Output;
/**
* Class DemoCommand
* @package Inhere\Console\Examples\Command
*/
class DemoCommand extends Command
{
protected static $name = 'demo';
protected static $description = 'this is a demo alone command. but config use configure(), like symfony console: argument define by position';
/**
* {@inheritDoc}
* @throws \LogicException
*/
protected function configure()
{
$this->createDefinition()
->setExample($this->parseCommentsVars('{script} {command} john male 43 --opt1 value1'))
->addArgument('name', Input::ARG_REQUIRED, 'description for the argument [name], is required')
->addArgument('sex', Input::ARG_OPTIONAL, 'description for the argument [sex], is optional')
->addArgument('age', Input::ARG_OPTIONAL, 'description for the argument [age], is optional')
->addOption('yes', 'y', Input::OPT_BOOLEAN, 'description for the option [yes], is boolean')
->addOption('opt1', null, Input::OPT_REQUIRED, 'description for the option [opt1], is required')
->addOption('opt2', null, Input::OPT_OPTIONAL, 'description for the option [opt2], is optional')
;
}
/**
* description text by annotation. it is invalid when configure() is exists
* @param Input $input
* @param Output $output
* @return int|void
*/
public function execute($input, $output)
{
$output->write('hello, this in ' . __METHOD__);
// $name = $input->getArg('name');
$output->write(<<<EOF
this is argument and option example:
the opt1's value
option: opt1 |
| |
php examples/app demo john male 43 --opt1 value1 -y
| | | | | |
script command | | |______ option: yes, it use shortcat: y, and it is a Input::OPT_BOOLEAN, so no value.
| |___ |
argument: name | argument: age
argument: sex
EOF
);
}
}
我的其他PHP项目
- inhere/kite 方便本地开发和使用的个人CLI工具应用
- php-toolkit/pflag PHP编写的,通用的命令行标志(选项和参数)解析库
- phppkg/easytpl 使用简单且快速的 PHP 模板引擎
- inhere/php-validate 一个简洁小巧且功能完善的php验证库
- inhere/sroute 轻量且快速的HTTP请求路由库