コマンド作成
下記コマンドでartisanコマンドを作成するためのファイルが生成される
$ php artisan make:command コマンド名
app/Console/Commands
配下にコマンド名.php
の形で下記ファイルが生成される
app/Console/Commands/コマンド名.php
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
class Scraping 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()
{
//
}
}
下記項目を追記する
-
$signature
にコマンド名を記述 -
$description
にコマンドの説明記述 -
public function handle()
内に実行スクリプトを記述
追記してみたファイル
app/Console/Commands/コマンド名.php
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
class Scraping extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'コマンド名'; // 追記
/**
* The console command description.
*
* @var string
*/
protected $description = 'コマンド名を実行します。'; // 追記
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
echo 'スクリプトを実行しました。' . PHP_EOL; // PHP_EOLの結合で改行が可能 // 追記
}
}
public function handle()
内を今回はサンプルでecho
を実行しているが、関数のスクリプトを記述すれば複雑な処理も実行される
コマンドの確認
設定したコマンドが設定されているか確認可能
# 使用可能なコマンドを確認できる
$ php artisan list
# 出力結果 (Available commands項目)
Available commands:
コマンド名 コマンド名を実行します # ここに表示される
clear-compiled Remove the compiled class file
down Put the application into maintenance mode
dump-server Start the dump server to collect dump information.
env Display the current framework environment
help Displays help for a command
inspire Display an inspiring quote
list Lists commands
migrate Run the database migrations
optimize Cache the framework bootstrap files
preset Swap the front-end scaffolding for the application
serve Serve the application on the PHP development server
tinker Interact with your application
up Bring the application out of maintenance mode
コマンドの実行
$ php artisan コマンド名
# 今回の場合の出力結果
スクリプトを実行しました
(参考)