Laravelでコンソールコマンドの作成方法を学んだのでアプトプットのため、記述しました。
コンソールコマンドの作り方
1 コンソールコマンドファイルの作成
php artisan make:command TextCommand
上記の例ではTextCommandという名前でapp/Console/ディレクトリーに作成されます。
2 コンソールコマンドファイルの編集
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
class TextCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
//コマンドを記述
protected $signature = 'text:make';
/**
* The console command description.
*
* @var string
*/
//説明を記述
protected $description = 'テキストファイルを作成するコマンド';
/**
* Execute the console command.
*
* @return int
*/
//実際の処理を記述
public function handle()
{
$filename = 'example.txt';
$content = '初めてLaravelのconsoleで作成しました。';
file_put_contents($filename, $content);
$this->info('できたで', $filename);
//info()の第一引数にはコンソールに表示させるメッセージを入れる,第二引数にはファイルの名前
}
}
3 Kanelファイルに登録
app/Conbsole/Kernel.phpに今、作成したコンソールコマンドファイルを登録します。
<?php
namespace App\Console;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
protected $commands = [
//ここ↓
Commands\TextCommand::class,
];
/**
* Define the application's command schedule.
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void
*/
//scheduleメゾットにはスケジュールなども設定することができます。
protected function schedule(Schedule $schedule)
{
// $schedule->command('inspire')->hourly();
}
/**
* Register the commands for the application.
*
* @return void
*/
protected function commands()
{
$this->load(__DIR__ . '/Commands');
require base_path('routes/console.php');
}
}
4 コンソールコマンドを実際に実行
php artisan text:make;
これでexample.txtが一番上の階層に作成されました。
ありがとうございました!