0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Laravelでコンソールコマンドの作り方

Posted at

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が一番上の階層に作成されました。

ありがとうございました!

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?