-
Notifications
You must be signed in to change notification settings - Fork 48
user interactive
Inhere edited this page Jan 10, 2019
·
1 revision
要独立使用的话需引入类
Inhere\Console\Util\Interact
,Controller
和Command
里可以直接调用相关方法
public static function read($message = null, $nl = false, array $opts = []): string
- 使用
$userInput = Interact::read();
// 先输出消息,再读取
$userInput = Interact::read('Your name:');
// 在 Controller/Command 中
$userInput = $this->read('Your name:');
public static function askHiddenInput(string $prompt = 'Enter Password:'): string
public static function askPassword(string $prompt = 'Enter Password:'): string
- 使用
$pwd = Interact::askPassword();
// 在 Controller/Command 中
$pwd = $this->askPassword();
public static function select($description, $options, $default = null, $allowExit=true)
public static function choice($description, $options, $default = null, $allowExit=true) // alias method
使用 Interact::select()
(alias Interact::chioce()
)
- 示例 1: 只有值,没有选项key
$select = Interact::select('Your city is ?', [
'chengdu', 'beijing', 'shanghai'
]);
渲染结果(in terminal):
Your city is ?
0) chengdu
1) beijing
2) shanghai
q) Quit // quit option. is auto add. can setting it by 4th argument.
You choice: 0
echo "$select"; // '0'
- 示例 2:
有选项key, 并且设置了一个默认值.
$select = Interact::select('Your city is ?', [
'a' => 'chengdu',
'b' => 'beijing',
'c' => 'shanghai'
], 'a');
渲染结果(in terminal):
Your city is?
a) chengdu
b) beijing
c) shanghai
q) Quit // quit option. is auto add. can setting it by 4th argument.
You choice[default:a] : b
echo $select; // 'b'
public static function confirm($question, $default = true) bool
使用 Interact::confirm()
:
$result = Interact::confirm('Whether you want to continue ?');
渲染结果(in terminal):
Whether you want to continue ?
Please confirm (yes|no) [default:yes]: n
结果:
var_dump($result); // bool(false)
public static function ask($question, $default = null, \Closure $validator = null)
public static function question($question, $default = null, \Closure $validator = null)
使用 Interact::question()
/Interact::ask()
$answer = Interact::ask('Please input your name?', null, function ($answer) {
if (!preg_match('/\w+/', $answer)) {
Interact::error('The name must match "/\w+/"');
return false;
}
return true;
});
public static function limitedAsk($question, $default = null, \Closure $validator = null, $times = 3)
有次数限制的询问,提出问题
- 若输入了值且验证成功则返回 输入的结果
- 否则,会连续询问
$times
次,若仍然错误,退出
// no default value
$answer = Interact::limitedAsk('please input you age?', null, function($age)
{
if ($age<1 || $age>100) {
Interact::error('Allow the input range is 1-100');
return false;
}
return true;
});
我的其他PHP项目
- inhere/kite 方便本地开发和使用的个人CLI工具应用
- php-toolkit/pflag PHP编写的,通用的命令行标志(选项和参数)解析库
- phppkg/easytpl 使用简单且快速的 PHP 模板引擎
- inhere/php-validate 一个简洁小巧且功能完善的php验证库
- inhere/sroute 轻量且快速的HTTP请求路由库