如何在laravel artisan控制台中将文件作为输入?

时间:2016-08-05 08:11:01

标签: php laravel laravel-5 artisan

我正在使用laravel应用程序,而不是只输入参数和选项,我想知道是否有一种方法可以输入文件。我希望从其他API导入大量数据,我使用Guzzle来做这件事。

很多时候,每次重置数据库时都会导入相同的数据。这就是我首先在json文件集合中导入数据然后每次使用该集合将数据插入数据库的原因,这样可以节省每次从其他API获取数据的时间。

现在我正在编写使用的文件的硬编码,但有没有办法可以通过命令行获取文件,我在其中指定控制台命令的参数和选项?

1 个答案:

答案 0 :(得分:2)

有很多方法可以做到这一点。

一种选择是将文件路径作为命令参数传递,然后使用基本的 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)并将该文件放在存储/应用文件夹中:

class YourCommand extends Command {
  public function fire() {
    dd(Storage::get($this->argument('path')));
  }

  protected function getArguments()
  {
      return [['path', InputArgument::REQUIRED, "File path"]];
  }
}

如果您想避免提供文件路径,最简单的方法是从STDIN流中读取文件:

class YourCommand extends Command {
  public function fire() {
    dd(file_get_contents('php://stdin');
  }
}

您只需要运行以下命令:

php artisan yourcommand < file.json