2016-08-05 87 views
2

我正在使用laravel应用程序,而不是仅输入参数和选项,我想知道是否有方法可以输入文件。我希望从其他API导入大量数据,并且我正在使用Guzzle来做到这一点。如何在laravel artisan控制台中输入文件作为输入?

在每个数据库重置时导入相同数据的时间很多。这就是为什么我首先将数据导入到json文件集合中,然后每次使用该集合将数据插入到数据库中,从而节省了每次从其他API获取数据的时间。

现在,我对使用的文件进行了硬编码,但是有没有一种方法可以通过命令行获取文件,其中我指定了控制台命令的参数和选项?

回答

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的Filesystem库,并建立本地存储(见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