Laravelユーザーには既知の通り、Artisanという便利なコマンドラインインターフェイスが存在します。
今回の目的は、独自コマンドを自作し、cronで定期実行することです。
以前紹介した、CSVデータ使ってデータベースへ自動でインポートするコマンドを作成します。
Artisanコマンドを作る
Artisanコマンドには、普段からよく使うコントローラーやモデルを作成するための[make:~]や、データベースを構築するための[migrate]が用意されています。
今回自作するコマンドは[command:~]を使って実行します。
例として、[importcsv]というコマンド名で作成することにします。
完成するとこのように実行します。
php artisan command:importcsv
独自コマンドを作成する
新しくコマンドを作成するにもコマンドを使いますww
それが、[make:command]です。
php artisan make:command ImportCsv
上記を実行すると[app/Console/Commands]直下に[ImportCsv.php]ファイルが生成されたと思います。
先に完成形を書いて、後程解説していきます。
app/Console/Commands/ImportCsv.php
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use App\Post;
use Excel;
class ImportCsv extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'command:importcsv';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Command description';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct(Post $post)
{
parent::__construct();
$this->post = $post;
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
$this->info('start!');
$fields = $this->post->getFillable();
$reader = Excel::load(storage_path('csv/data.csv'));
$rows = $reader->toArray();
$this->info('data.csv: '.count($rows).'rows');
foreach ($rows as $row){
$id = $row[0];
$record = $this->post->firstOrNew(['post_id' => $id]);
foreach ($row as $key => $value) {
$colmun = $fields[$key];
$record->$colmun = $value;
}
$record->save();
$this->info('Import Done: data.csv');
Log::info('Import Done: data.csv');
}
$this->info('Done!');
Log::info('Import Done: End');
}
}
解説
まずは使いたいモデルやパッケージを読み込みます。
use App\Post;
use Excel;
[$signature]変数に実際叩く時のコマンド名を設定します。
protected $signature = 'command:importcsv';
このように設定すると、冒頭でもお伝えした通り、
php artisan command:importcsv
で、コマンドを実行することができます。[$description]にはコマンドの説明を追加します。(任意です)
protected $description = 'これはCSVデータをデータベースにインポートするためのコマンドです';
例としてPostモデルを使うとためにコンストラクタを追加しています。
public function __construct(Post $post)
{
・・・
$this->post = $post;
}
実際の処理はhandle()に記述します。
public function handle()
{
・・・
}
内容は以前と同じものですが、コンソール画面にメッセージを表示する、またログを出力するために少し手を加えてます。
※詳細は下記のコントローラー内のimport()を参照
進行状況、エラーの表示
進行状況をコンソール画面に表示するには、以下のメソッドを使います。
$this->info('message');
他にも、line、comment、question、errorメソッドが用意されています。
違いがよくわかりませんが、色が変わるようです。また、ログを出力するには以下のようにします。
Log::info('message');
こちらも種類がありますので状況によって使い分けてください。
Log::emergency($message);
Log::alert($message);
Log::critical($message);
Log::error($message);
Log::warning($message);
Log::notice($message);
Log::debug($message);



コメント