====== 16 Laravel コマンドラインアプリケーション ======
===== Commandクラス作成 =====
$ php artisan make:command sample/test
$ ll app/Console/Commands/sample/test.php
-rw-r--r-- 1 matsui users 677 Jan 30 16:01 app/Console/Commands/sample/test.php
===== Commandのシグネチャ変更 =====
protected $signature = 'command:name';
↓
protected $signature = 'command:test';
protected $description = 'Command description';
↓
protected $description = 'てすとコマンド';
===== Commandクラスをartisanコマンドとして登録 =====
protected $commands = [
//
];
↓
protected $commands = [
Commands\sample\test::class
];
===== Command確認 =====
$ php artisan
・
・
・
command
command:test てすと
・
・
・
===== 引数を指定する場合 =====
必須引数
protected $signature = 'command:test {arg}';
任意引数
protected $signature = 'command:test {arg?}';
デフォルト値の指定
protected $signature = 'command:test {arg=argument}';
引数に説明を付ける場合
protected $signature = 'command:test {arg : 引数を指定}';
例:
$ php artisan command:test -h
Description:
てすとコマンド
Usage:
command:test
Arguments:
arg 引数を指定
==== 引数実行時の取得 ====
public function handle()
{
$name = $this->argument("name");
$this->info("Hello $name");
}
===== オプションを指定する場合 =====
オプション指定
protected $signature = 'command:test {--dry-run}';
値指定オプション
protected $signature = 'command:test {--dry-run=}';
デフォルト値オプション
protected $signature = 'command:test {--dry-run=1}';
オプションに説明を追加
protected $signature = 'command:test {--dry-run : 実行テスト}';
オプションにショートカット指定
protected $signature = 'command:test {--d|--dry-run : 実行テスト}';
例:
$ php artisan command:test -h
Description:
てすとコマンド
Usage:
command:test [options]
Options:
-d, --dry-run 本番実行
==== オプション実行時の取得 ====
public function handle()
{
$dry_run = $this->option("dry-run");
$this->info("Option $dry_run");
}
===== コンソール出力 =====
public function handle()
{
$this->info('info');
$this->line('line');
$this->comment('comment');
$this->question('question');
$this->error('error');
$this->table(
['名前', '年齢'],
[
['Taro', 10],
['Laravel', 5],
]
);
}
===== artisanコマンドからartisanコマンドを呼び出す方法 =====
=== $this->call ===
$this->call('command:called', ['--path' => 'call']);
=== Artisan::call ===
use \Artisan;
// 実行
Artisan::call('command:called', ['--path' => 'artisan']);
{{tag>laravel php}}