Help us understand the problem. What is going on with this article?

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

はじめに

こちらの記事は、社内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

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした