Quantcast
Channel: 初心者タグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 21093

Laravel Commandを実装する(超初歩)

$
0
0

目的

  • Laravelにてコマンドを作成する方法をまとめる

実施環境

  • ハードウェア環境(下記の二つの環境で確認)
項目情報
OSmacOS Catalina(10.15.3)
ハードウェアMacBook Pro (16-inch ,2019)
プロセッサ2.6 GHz 6コアIntel Core i7
メモリ16 GB 2667 MHz DDR4
グラフィックスAMD Radeon Pro 5300M 4 GB Intel UHD Graphics 630 1536 MB
  • ソフトウェア環境
項目情報備考
PHP バージョン7.4.3Homwbrewを用いて導入
Laravel バージョン7.0.8commposerを用いて導入
MySQLバージョン8.0.19 for osx10.13 on x86_64Homwbrewを用いて導入

概要

  • ターミナルに「Test」と文字列を出力するだけのLaravelコマンドを作成する。
  • コマンド名は「app:test」とする。
  1. クラスの作成
  2. コマンドの内容の実行内容記載
  3. 確認

詳細

  1. クラスの作成

    1. アプリ名ディレクトリで下記コマンドを実行してクラスを作成する。(クラスの命名方法はキャメルケースを用いる)

      $php artisan make:command TestCommand
      
    2. 下記にクラスが記載されているファイル「TestCommand.php」が作成されている事を確認する。

      • アプリ名ディレクトリ/app/Console/Commands
  2. コマンドの内容の実行内容記載

    1. アプリ名ディレクトリで下記コマンドを実行してクラスが記載されているファイルを開く。

      $vi app/Console/Commands/TestCommand.php
      
    2. 開いたクラスファイルを下記の様に修正する。

      <?php
      
      namespace App\Console\Commands;use Illuminate\Console\Command;
      class TestCommand extends Command
      {
          /**
           * The name and signature of the console command.
           *
           * @var string
           */
      //    protected $signature ='command:name';   //上記の行をコメントアウト、もしくは削除して下記の行を追加
          protected $signature ='app:test';
          /**
           * The console command description.
           *
           * @var string
           */
      //    protected $description ='Command description';    //上記の行をコメントアウト、もしくは削除して下記の行を追加
          protected $description ='ターミナル上に"Test"と出力するコマンド';
          /**
           * Create a new command instance.
           *
           * @return void
           */
          public function __construct()
          {
              parent::__construct();    }
      
          /**
           * Execute the console command.
           *
           * @return mixed
           */
          public function handle()
          {
              //下記を追加
              $this->info('Test');    }
      }
      
  3. 確認

    1. アプリ名ディレクトリで下記コマンドを実行して現在使用可能なコマンドの一覧を表示する。

      $php artisan list
      
    2. 先のコマンドを出力結果の中に下記の記載が存在する事を確認する。

      app
       app:test             コマンドの実装方法を確認するコマンド
      
    3. アプリ名ディレクトリで下記コマンドを実行してターミナル上に「Test」と出力される事を確認する。

      $ php artisan app:test
      Test
      

Viewing all articles
Browse latest Browse all 21093

Trending Articles