gpt4 book ai didi

php - 如何通过交互调用 artisan 控制台命令

转载 作者:可可西里 更新时间:2023-10-31 22:52:46 25 4
gpt4 key购买 nike

我目前正在 Laravel 5.1 项目中创建一个 php artisan 控制台命令,并且想从我的控制台命令调用另一个控制台命令。我要调用的这个第三方命令不接受任何选项或参数,而是通过交互式问题接收其输入。

我知道我可以调用带有如下选项和参数的命令:

$this->call('command:name', ['argument' => 'foo', '--option' => 'bar']);

我也知道我可以调用交互式命令,而无需像这样从命令行进行交互:

php artisan command:name --no-interaction


但是我怎样才能在我的命令中回答这些交互式问题呢?

我想做类似下面的事情(伪代码)。

$this->call('command:name', [
'argument' => 'foo',
'--option' => 'bar'
], function($console) {
$console->writeln('Yes'); //answer an interactive question
$console-writeln('No'); //answer an interactive question
$console->writeln(''); //skip answering an interactive question
} );

当然上面的方法不起作用,因为 $this->call($command, $arguments) 不接受第三个回调参数。

从控制台命令调用控制台命令时如何回答交互式问题?

最佳答案

我有另一个解决方案,它是调用一个执行“php artisan”的 symfony 命令,而不是使用 artisan 子命令。我认为这比修补第 3 方代码更好。

这是管理这个的特征。

use Symfony\Component\Process\Process;
use Symfony\Component\Process\Exception\ProcessFailedException;
trait ArtisanCommandTrait{
public function executeArtisanCommand($command, $options){
$stmt = 'php artisan '. $command . ' ' . $this->prepareOptions($options);

$process = new Process($stmt);
$process->run();
// executes after the command finishes
if (!$process->isSuccessful()) {
throw new ProcessFailedException($process);
}
return $process->getOutput();
}
public function prepareOptions($options){
$args = [];
$opts = [];
$flags = [];
foreach ($options as $key => $value) {
if(ctype_alpha(substr($key, 0, 1)))
$args[] = $value;
else if(starts_with($key, '--')){
$opts[] = $key. (is_null($value) ? '' : '=' . $value) ;
}
else if(starts_with($key, '-')){
$flags[] = $key;
}
}
return implode(' ', $args) . ' '
.implode(' ', $opts). ' '
.implode(' ', $flags);
}
}

现在,您应该能够传递任何 artisan 特殊选项,例如无交互。

public function handle(){
$options = [
'argument' => $argument,
'--option' => $options, // options should be preceded by --
'-n' => null // no-interaction option
];
$command = 'your:command';
$output = $this->executeArtisanCommand($command, $options);
echo $output;
}

您可以从这个 gist 下载特征

关于php - 如何通过交互调用 artisan 控制台命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34199227/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com