LaravelでコマンドAPIを作成
Laravelの基本的な部分が少しわかったので、早速色々作っていきたいと思っています。環境は以下の通りです。
- PHP 7.2.0
- Laravel 5.5.28
最終的にはWebアプリを作っていきたいのですが、まずはCronで実行するスクリプトを作りたいと思っているのでその作り方をメモしておきます。
コマンドの作成
artisanでコマンドを作成します。
vagrant@homestead:~/code/laravel$ php artisan make:command TestCommands Console command created successfully.
上記のコマンドで、app/Console/Commands/TestCommands.php
が作成されます。
作成されたファイルは以下のようになっています。
<?php namespace App\Console\Commands; use Illuminate\Console\Command; class TestCommands extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'command:name'; /** * 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 handle() { // } }
コマンド名の変更
TestCommands.php
の$signatureに名前が定義されています。デフォルトではcommand:name
となっていますので、任意の名前に変更します。
protected $signature = 'testcommand';
デフォルト設定のようにcommand:name
の形にすると、commandと言う名前空間(グループ?)のnameと言うコマンドで登録されます。
コマンドの登録
作成したコマンドをartisanのコマンドとして登録します。app/Console/Kernel.php
に記述することで登録可能です。
$commandsに、コマンドを追加します。
protected $commands = [ Commands\TestCommands::class ];
コマンドの確認
コマンドとして登録されているか、artisan list
コマンドで確認します。
testcommand
が登録されていればOKです。
処理の記述
実際のコマンドの処理は、handleメソッドに追加していきます。慣例に習って、hello worldでいきます。
app/Console/Commands/TestCommands.php
のhandleを以下のようにします。
<?php /** * Execute the console command. * * @return mixed */ public function handle() { echo "hello world \n"; }
コマンド実行
artisan testcommand
を実行すると、無事にhello worldが実行されました。
vagrant@homestead:~/code/laravel$ php artisan testcommand
hello world