如何以编程方式调用交互式Laravel Artisan命令并自动应答
解决Laravel中编程式调用交互式Artisan命令并自动回答的问题
要自动处理交互式Artisan命令的提问,核心是借助Symfony Console组件的输入流模拟功能,以下是具体实现方案:
基础实现(适用于控制器、任务等环境)
通过StringInput模拟用户输入的内容,按命令的交互顺序将答案用换行符分隔,配合BufferedOutput还可获取命令执行后的输出:
use Illuminate\Support\Facades\Artisan; use Symfony\Component\Console\Input\StringInput; use Symfony\Component\Console\Output\BufferedOutput; // 构造输入:命令名 + 按顺序的回答(每个回答后加换行符) $inputContent = 'say:hello' . PHP_EOL . 'John Doe'; $input = new StringInput($inputContent); $output = new BufferedOutput(); // 执行命令 Artisan::getApplication()->run($input, $output); // 获取命令输出结果(可选) $outputText = $output->fetch(); // 输出示例:Hello, John Doe!
针对不同交互类型的处理
根据命令中使用的交互方法,对应传入不同的输入内容:
- ask() 文本提问:直接传入回答内容+换行
- confirm() 确认提问:传入
y/yes(确认)或n/no(取消)+换行 - choice() 选择提问:传入选项的序号(如
0)或选项值+换行
示例:如果命令包含确认和选择交互,输入内容如下:
// 假设命令逻辑:先确认是否继续,再选择性别 $inputContent = 'user:create' . PHP_EOL . 'y' . PHP_EOL . '1';
简化调用方式(直接解析命令)
也可以直接解析目标命令,设置输入后执行:
use Illuminate\Support\Facades\Artisan; use Symfony\Component\Console\Input\StringInput; $command = Artisan::resolve('say:hello'); // 注意:这里的输入只需要回答内容,不需要命令名 $command->setInput(new StringInput('John Doe' . PHP_EOL)); $command->handle();
内容的提问来源于stack exchange,提问作者TheSETJ
相关产品推荐
相关产品推荐

