Skip to content

user interactive

Inhere edited this page Jan 10, 2019 · 1 revision

用户交互方法

要独立使用的话需引入类 Inhere\Console\Util\InteractControllerCommand 里可以直接调用相关方法

读取用户输入

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;
});