16
14

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

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

Last updated at Posted at 2014-02-24
  • artisanコマンドクラス作成
  • ファサード作成
    を試してみる

公式ドキュメント

ドキュメント 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ジョブやインポートなどのバッチジョブなどの自動更新タスクに使用

実践

レイアウト

```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 ```

ImportCommand.php

```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);
            }
 
        });
 
    }
}

Facades/Importer.php

```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__)); 
    }
}

Services/Hoge.php

```php class Hoge extends AbstractImporter { } ```

Services/Moge.php

```php class Moge extends AbstractImporter { } ```

command から commandを呼ぶ

```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を呼ぶことができるので、順番を制御も容易

などが魅力ですね。
16
14
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
16
14

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?