我可以使用以下代码获取命令中的参数:
$this->argument();
Run Code Online (Sandbox Code Playgroud)
但如何引起外界的争论呢?
如果我查看 argument() 函数的来源,我会看到:
public function argument($key = null)
{
if (is_null($key)) {
return $this->input->getArguments();
}
return $this->input->getArgument($key);
}
Run Code Online (Sandbox Code Playgroud)
我想检测命令“php artisan migrate:refresh --seed”何时运行,因为我希望模型中的某些代码在本地主机环境中运行,但在播种期间不在本地主机环境中运行...
Laravel 获取命令参数的机制相当复杂。我可以使用 \App::runningInConsole() 检测应用程序是否在控制台中运行,但没有函数可以获取参数,例如:
if(\App::runningInConsole()){
$args = \App::getConsoleArguments(); // doesn't exist :(
}
Run Code Online (Sandbox Code Playgroud)
但是 $_SERVER['argv'] 在这里可能很有用,当“php artisan migrate:refresh --seed”在 $_SERVER['argv'] 中运行时是这个数组:
Array
(
[0] => artisan
[1] => migrate:refresh
[2] => --seed
)
Run Code Online (Sandbox Code Playgroud)
所以我可以使用这段代码:
if( ! empty($_SERVER['argv'][2] ) && $_SERVER['argv'][2] == '--seed'){
//
}
Run Code Online (Sandbox Code Playgroud)