2016-08-05 38 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