Laravel Artisan 命令行:询问 / 交互式输入 1 个改进

问题

Artisan 命令能否实现以问答方式来让用户输入数据,比如询问用户的用户名,询问用户要统计的日期等等?

回答

Artisan 命令提供了丰富的辅助方法,来完成与用户交互。

ask 方法

ask 方法提示并等待用户输入,然后用户的输入将会传入你的命令:

$name = $this->ask('What is your name?');

secret 方法

ask 方法类似,只不过用户在控制台输入时他们的输入内容是不可见的。这个方法适用于需要用户输入像密码这样的敏感信息的时候:

$password = $this->secret('What is the password?');

confirm 方法

如果想要用户对操作进行确认,可以使用 confirm 方法。默认情况下,该方法将返回 false 。但如果用户在回复中输入 y 或者 yes 则会返回 true

if ($this->confirm('Try again?')) {
    //
}

anticipate 方法

anticipate 方法可用于为可能的选择提供自动补全功能。用户仍然可以忽略自动补全的提示,作任意回答:

$from = $this->anticipate('where are you from?', ['Beijing', 'Shanghai']);

综合实例

Artisan::command('demo:interactive', function () {

    do {
        $name = $this->ask('What is your name?');

        $password = $this->secret('What is the password?');

        if ($password !== '123456') {
            $this->error("$name's password error");
        }

        $from = $this->anticipate('where are you from?', ['Beijing', 'Shanghai']);

        $this->comment("You are from $from");

        if (!$this->confirm('Try again?')) {
            $this->info('Byebye');
            break;
        }
    } while (true);

})->describe('Demo various interactive methods');

效果:

参考

本文为 Wiki 文章,邀您参与纠错、纰漏和优化
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!