Laravel4のartisanコマンドクラス、ファサードを使用してのバッチ処理の作成

- artisanコマンドクラス作成
- ファサード作成
を試してみる

<h2>公式ドキュメント</h2>

|ドキュメント|URL|
|:-----------|:------------|
|Laravel4|http://laravel.com/docs/commands|
|illuminate|https://github.com/illuminate/console/blob/master/Command.php|
|symfony2 Console|http://docs.symfony.gr.jp/symfony2/components/console/introduction.html|

>コンソールコマンドは、cronジョブやインポートなどのバッチジョブなどの自動更新タスクに使用

<h2>実践</h2>
<h4>レイアウト</h4>
```php
/laravel/myproj/app
    + commands
        + ImportCommand.php
        + ImportDailyCommand.php
        + Importer/
            + Facades/
                + Importer.php
            + ImporterServiceProvider.php
            + Services/
                + AbstractImporter.php
                + Hoge.php
                + Moge.php
    + config
        + development/
    + controllers
    + storage/logs/laravel.log
```

<h4>ImportCommand.php</h4>
```php
class ImportCommand extends Command {
 
        protected $name = 'command:import';
 
        public function fire()
        {
            $name = $this->option('name');
            $type= $this->option('type');
            $yyyymmdd = $this->option('yyyymmdd');
 
            $app = $this->getLaravel();
            $importer = $app->make('importer', $options)->execute(); 
        }
 
        protected function getOptions()
        {
            return array( array('name', 'k', InputOption::VALUE_REQUIRED, 'A name option.', null),
                   array('type', 'c', InputOption::VALUE_OPTIONAL, 'A typeoption. [d,a,s,all]', 'all'),
                   array('yyyymmdd', 'd', InputOption::VALUE_OPTIONAL, 'A yyyymmdd option.', Carbon::yesterday()->format("Ymd")) )

        }
}

```

<h2>コマンドの実行</h2>
```
/usr/local/bin/php artisan command:import
```

オプション引数を確認
/usr/local/bin/php artisan command:import -h

```
Usage:
command:import [-k|--name="..."] [-d|--yyyymmdd[="..."]] [-c|--type[="..."]]
Options:
 --name (-k)           A name option.
 --yyyymmdd (-d)       A yyyymmdd option. (default: "20140213")
 --type (-c)           A type option. [d,a,s,all] (default: "all")
 --help (-h)           Display this help message.
 --quiet (-q)          Do not output any message.
 --verbose (-v|vv|vvv) Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug
 --version (-V)        Display this application version.
 --ansi                Force ANSI output.
 --no-ansi             Disable ANSI output.
 --no-interaction (-n) Do not ask any interactive question.
 --env                 The environment the command should run under.
```
–env=development を指定すると
config/development/　の環境のconfigを参照し実行してくれる

<h2>ファサードを試してみる</h2>
http://laravel4.kore1server.com/docs/40/facades
>ファサードはアプリケーションのIoCコンテナに用意したクラスに「静的」なインターフェイスを提供してくれます。

- ServiceProviderを編集する
- Facadeを作る
- クラスを作る

<h4>ImporterServiceProvider.php</h4>
```php
use Illuminate\Support\ServiceProvider;
 
class ImporterServiceProvider extends ServiceProvider
{
 
    public function register()
    {
 
        $this->app->bind('importer', function ($app, $options) {
 
            switch ($options['name']) {
                case "hoge":
                    return new Services\hoge($options);
                case "moge":
                    return new Services\moge($options);
            }
 
        });
 
    }
}
```

<h4>Facades/Importer.php</h4>
```php
class Importer extends \Illuminate\Support\Facades\Facade
{
    /**
     * Get the registered name of the component.
     *
     * @return string
     */
    protected static function getFacadeAccessor() { return 'importer'; }
 
}
```

<h4>Services/AbstractImporter.php</h4>
```php
class AbstractImporter
{
 
    public function __construct($options)
    {
        \Log::info(sprintf("%s::%s()", get_called_class(), __FUNCTION__) , $options); 
    }
 
    public function execute()
    {
 
        \Log::info(sprintf("%s::%s()", get_called_class(), __FUNCTION__)); 
    }
}
```

<h4>Services/Hoge.php</h4>
```php
class Hoge extends AbstractImporter
{
}
```

<h4>Services/Moge.php</h4>
```php
class Moge extends AbstractImporter
{
}
```

<h2>command から　commandを呼ぶ</h2>
```php
use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;
 
class ImportDailyCommand extends Command
{
    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'command:importDaily';
 
    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description.';
 
    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }
 
    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function fire()
    {
        //
        $yyyymmdd = $this->option('yyyymmdd');
  
        $nameList = [
            'hoge',
            'moge',
        ];
 
        foreach ($nameList as $name) {
            $this->call('command:import', array('--name' => $name , '--yyyymmdd' => $yyyymmdd));
        }
    }
 
    /**
     * Get the console command arguments.
     *
     * @return array
     */
    protected function getArguments()
    {
        return array(
//            array('example', InputArgument::REQUIRED, 'An example argument.'),
        );
    }
 
    /**
     * Get the console command options.
     *
     * @return array
     */
    protected function getOptions()
    {
        return array(
            array('yyyymmdd', 'd', InputOption::VALUE_OPTIONAL, 'A yyyymmdd option.', Carbon::yesterday()->format("Ymd")),
        );
    }
}
```

<h3>実行</h3>
```
php artisan command:importDaily
```

<h4>storage/logs/laravel.log</h4>
```
[2014-02-14 12:18:43] production.INFO: Importer\Services\Hoge::__construct() ["hoge","all","20140214"] []
[2014-02-14 12:18:43] production.INFO: Importer\Services\Hoge::execute() [] []
[2014-02-14 12:18:43] production.INFO: Importer\Services\Moge::__construct() ["moge","all","20140214"] []
[2014-02-14 12:18:43] production.INFO: Importer\Services\Moge::execute() [] []
```

command:import –name=hoge, command:import –name=mogeが実行される

<h4>実践しみたところでは、</h3>

- オプション引数が分かりやすくなる
- 引数やサブコマンドの候補も補完してくれる
- command から　callメソッドでcommandを呼ぶことができるので、順番を制御も容易

などが魅力ですね。