LoginSignup
1
1

More than 3 years have passed since last update.

Laravel 5.8でオリジナルのイベントを定義してみた話

Posted at

はじめに

こちらの記事は、社内knowledgeからの移行記事になります。

Laravelで自作イベントを定義するまでの一連の流れ。

【参考にした公式】

【参考記事】
- Laravel5.7でEventを利用してみる - qiita

【ソース】
- GitHub

環境

  • Laravel 5.8.23

本編

1.イベントとリスナをサービスプロバイダに定義

application/app/Providers/EventServiceProvider.php
protected $listen = [
    'App\Events\TaxIncreased' => [
        'App\Listeners\TaxIncreasedNotification'
    ],
];

2.Artisanコマンドでイベントとリスナを作成

# php artisan event:generate
Events and listeners generated successfully!

3.リスナにイベント処理を定義

今回は発生したイベントのオブジェクトを返すだけ。

application/app/Listeners/TaxIncreasedNotification.php
public function handle(TaxIncreased $event)
{
    return $event;
}

4.イベントを定義

application/app/Events/TaxIncreased.php
public $name;
public $price;
public $taxRate;
public $taxIncludingPrice;

/**
 * TaxIncreased constructor.
 *
 * @param string $name
 * @param int $price
 * @param bool $isReduceTax
 */
public function __construct(string $name, int $price, bool $isReduceTax){
    $this->name  = $name;
    $this->price = $price;
    $this->taxRate = ($isReduceTax) ? 0.08 : 0.10;
    // 税込み価格計算
    $this->taxIncludingPrice = (int) $this->price * ( 1 + $this->taxRate);
}

5.イベントを呼び出す

今回はコントローラのアクションからイベントを呼び出す。

application/app/Http/Controllers/HomeController.php
 public function index()
 {
     $eatIn   = event(new TaxIncreased('タピオカ',1000,false))[0];
     $takeOut = event(new TaxIncreased('タピオカ',1000,true ))[0];

     return view('home',compact(['eatIn','takeOut']));
 }

結果

軽減税率イベントが発火した。

image01.png

1
1
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
1
1