Laravel Artisan 命令行:获取选项
问题
我如何在命令中获取用户输入的选项?
回答
不论是在命令类文件中,还是在闭包命令中,你都可用 option 方法来获取用户输入的特定选项。
假设我们在命令类的 handle() 方法中要获取用户输入的 uppercase 选项:
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
$uppercase = $this->option('uppercase');
}
如果你想一次性获取所有的选项,可以调用 options 方法,它返回一个包含所有选项的数组:
$options = $this->options();
$this->info($options['uppercase']);
注意:这里说的包含所有选项,是指包含所有你在创建命令时定义的选项,还包括继承的 help、quiet、verbose、version、ansi 等选项。
不管是 option 还是 options 方法,如果用户没有输入这个选项,有默认值的,返回默认值,否则返回 NULL,对于开关选项,值为 false。
在闭包命令中,除了象命令类那样通过 $option 和 options 方法来获取用户输入的选项外,还可以直接在闭包函数的参数列表中列出要使用的选项:
方式一:
Artisan::command('hash:md5 {text} {--uppercase}', function () {
$text = $this->argument('text');
$uppercase = $this->option('uppercase');
$md5text = $uppercase ? strtoupper(md5($text)) : md5($text);
$this->info("md5('{$text}') = $md5text");
})->describe('Calculate the md5 hash of a text');
方式二:
Artisan::command('hash:md5 {text} {--uppercase}', function ($text, $uppercase) {
$md5text = $uppercase ? strtoupper(md5($text)) : md5($text);
$this->info("md5('{$text}') = $md5text");
})->describe('Calculate the md5 hash of a text');
Laravel 社区 Wiki
关于 LearnKu
推荐文章: