【问题标题】:How to take a file as input in laravel artisan console?如何在 laravel artisan 控制台中将文件作为输入?
【发布时间】:2016-12-11 13:55:11
【问题描述】:
我正在使用 laravel 应用程序,我不只是输入参数和选项,而是想知道是否有一种方法可以输入文件。我希望从其他 API 导入大量数据,我正在使用 Guzzle 来做到这一点。
很多时候,每次数据库重置时都会导入相同的数据。这就是为什么我先将数据导入到一个 json 文件集合中,然后我每次都使用该集合将数据插入到数据库中,这样可以节省每次从其他 API 获取数据的时间。
现在我正在对所使用的文件进行硬编码,但有没有一种方法可以通过命令行获取文件,我在命令行中为控制台命令指定参数和选项?
【问题讨论】:
标签:
php
laravel
laravel-5
laravel-artisan
【解决方案1】:
有很多方法可以做到这一点。
一种选择是将文件路径作为命令参数传递,然后使用基本的 file_get_contents() 函数读取文件。
class YourCommand extends Command {
public function fire() {
dd(file_get_contents($this->argument('path'));
}
protected function getArguments()
{
return [['path', InputArgument::REQUIRED, "File path"]];
}
}
您还可以使用 Laravel 的文件系统库并设置本地存储(请参阅https://laravel.com/docs/5.1/filesystem 了解更多详细信息)并将文件放入您的 storage/app 文件夹:
class YourCommand extends Command {
public function fire() {
dd(Storage::get($this->argument('path')));
}
protected function getArguments()
{
return [['path', InputArgument::REQUIRED, "File path"]];
}
}
如果您想避免提供文件路径,最简单的方法是通过从 I/O 流中检索内容来从 STDIN 流中读取文件:
class YourCommand extends Command {
public function fire() {
dd(file_get_contents('php://stdin'));
}
}
您只需要运行如下命令:
php artisan yourcommand < file.json