Hiroto's diary

プログラミングとか色々

LaravelのartisanコマンドでgetArguments()やgetOptions()を使う時はコマンド名の指定に$nameを使う必要がある

LaravelのArtisanで自作Commandクラスを使う時に躓いたのでメモ

LaravelでArtisanコマンドを作る時に以下のようにコマンド名を指定する($signatureを使う)とgetArguments()getOptions()が読まれない。

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

class HogeCommand extends Command {

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = "test:hoge";

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = "Test command";

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle() {
        dd($this->argument());
    }

    /**
     * Get the console command arguments.
     *
     * @return array
     */
    protected function getArguments() {
        return [
            ["files", InputArgument::IS_ARRAY, "Files"],
        ];
    }

}

これでtest:hogeコマンドを実行してもfiles引数は読まれない。

理由

HogeCommand内でコマンド名の指定に$signatureを使っているから。

$signatureでの指定は以下のリンクにあるように、$signatureで名前だけでなく引数やオプションも指定する時に使う。

http://readouble.com/laravel/5/1/ja/artisan.html

修正する

$signatureでは無く$nameでコマンド名を定義すればgetArguments()getOptions()が読まれる。

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

class HogeCommand extends Command {

    /**
     * The name of the console command.
     *
     * @var string
     */
    protected $name = "test:hoge";

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = "Test command";

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle() {
        dd($this->argument());
    }

    /**
     * Get the console command arguments.
     *
     * @return array
     */
    protected function getArguments() {
        return [
            ["files", InputArgument::IS_ARRAY, "Files"],
        ];
    }

}

これでfiles引数が動く

© 2015 hiroxto