LoginSignup
36
37

More than 5 years have passed since last update.

Laravelのartisanでバッチ処理

Last updated at Posted at 2014-04-17

Laravelでバッチ処理を書いた時のメモ

■artisanに登録する
app/start/artisan.php

artisan.php
Artisan::add(new \commands\TestCommand());

■処理を記述
app/commands/TestCommand.phpに処理を記述
・Illuminate\Console\Commandを継承する
・fire()にメイン処理を記述する
・getArguments()に引数の設定を記述
・getOptions()にオプションの設定を記述

TestCommand.php
namespace commands;

use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;
use models\batch\BatchTestModel;

class TestCommand extends Command
{
    protected $name = 'batch:test';
    protected $description = 'アーティザンのテスト';

    public function fire()
    {
        // 全ての引数を取得する
        $argument = $this->argument();

        // 引数を全て表示してみる
        $this->info(json_encode($argument));

        // Modelを呼び出してみる
        $exec = new BatchTestModel();
        $exec->execute($argument());

    }


    /**
     * 受け取る引数の設定
     * @return array
     */
    protected function getArguments()
    {
        return [
            ['argument1', InputArgument::REQUIRED, '引数の説明・・・必須'],
            ['argument2', InputArgument::OPTIONAL, '引数の説明・・・任意']
        ];
    }

    /**
     * 受け取るオプションの設定
     * @return array
     */
    protected function getOptions()
    {
        return [
            ['example1', 'e', InputOption::VALUE_REQUIRED, 'オプションの説明・・・必須'],
            ['example2', 'f', InputOption::VALUE_OPTIONAL, 'オプションの説明・・・任意']
        ];
    }
}

■artisanコマンドで処理を実行する

$ php artisan batch:test --example1 option1 -f option2 value1 value2
{"command":"batch:test","argument1":"value1","argument2":"value2"}
["option1","option2"]

------おまけ------
■使用できるartisanコマンドの一覧を表示してみる
TestCommand.phpの
・protected $name
・protected $description
で設定した内容が一覧表示される。

$ php artisan list
・・・省略
batch
  batch:test                  アーティザンのテスト

■ヘルプを表示
helpコマンド打つとTestCommand.phpの内容を読み取り使用方法が出力される

$ php artisan batch:test --help

Usage:
 batch:test [-e|--example1="..."] [-f|--example2[="..."]] argument1 [argument2]

Arguments:
 argument1             引数の説明・・・必須
 argument2             引数の説明・・・任意

Options:
 --example1 (-e)       オプションの説明・・・必須
 --example2 (-f)       オプションの説明・・・任意
 --help (-h)           Display this help message.
・・・以下省略
36
37
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
36
37