Laravelでコマンドラインの機能をつくってみる

環境はPHP8.3とlaravel11です。
1. コマンド処理をするファイルの作成
まずはコマンド処理をするファイルを作ります。
artisanコマンドで出来ます。
php artisan make:command Sample
そうすると、「app/Console/Commands」にSample.phpができました。
中身はこんな感じです。
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
class Sample extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'app:sample';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Command description';
/**
* Execute the console command.
*/
public function handle()
{
//
}
}
handleは実行したときの処理を書くみたいなのですが、
今は何も書かれていないので、実行しても何も起きませんね。
なので、handleの部分に以下を追記します。
public function handle()
{
$this->comment('Sample!!');
}
ここでは「Sample!!」とコメントを出すようにしています。
では実行してみます。まずはコマンドの確認。
php artisan list
「app:sample」がありました。
これは、protected $signature = ‘app:sample’; で指定されている部分ですね。
ということでこんな感じで実行してみます。
php artisan app:sample
こんな感じで表示されました。
Sample!!
無事成功ですね!
2. ファイルの場所を変更
さきほどのように通常の方法で作ったファイルは、
自動的に「app/Console/Commands」に作られ、
さらにそこにあるものだけしか読み込まれないし、実行できないみたいです。
でも他のディレクトリに移動させたかったので、試してみました。
今回指定する場所は「origin/Console/Commands」にしました。
まずはoriginへのパスを「composer.json」に追記します。
これをやらないとファイルが読み込まれないみたいです。
Appの下にOriginを追加します。
"autoload": {
"psr-4": {
"App\\": "app/",
"Origin\\": "origin/",
"Tests\\": "tests/",
"Database\\Factories\\": "database/factories/",
"Database\\Seeders\\": "database/seeders/"
},
※一部抜粋
では次にさっき作った「app/Console/Commands/Sample.php」ファイルを
移動して以下に書き換えます。
namespaceのパスを変えるだけです
<?php
namespace Origin\Console\Commands;
use Illuminate\Console\Command;
class Sample extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'app:sample';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Command description';
/**
* Execute the console command.
*/
public function handle()
{
$this->comment('Sample!!');
}
}
次にコマンドファイルを新たに読み込ませる指定です。
「bootstrap/app.php」に追記します。
use Origin\Sample;
return Application::configure(basePath: dirname(__DIR__))
// 独自のコマンドファイル郡を指定
->withCommands([
Sample::class,
])
...
コマンドファイルをuseして、withCommandsにクラス名を指定します。
そしてcomposerを再読み込み。
composer dump-autoload
これをやらないとファイルが読み込まれないみたいですね。
これで「php artisan list」で見てみてみます。
「app」に「sample」が入っていますね。
実行してみます。
php artisan app:sample
Sample!!
無事に実行されました!
これでどこでも自由に配置できるようになりましたね。
今回は以上です!