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?

イベントの使い方

Posted at

はじめに

イベントというワードはよく聞いていたが、実際に使ったことがなかったので、今回使ってみました。

使い方

今回は、ユーザーが作成されたら、その作成されたユーザーのIDをログに出すという題材でやって来たいと思います。
Laravelの環境に関しては各自用意をお願いします。

Step 1: イベントとリスナーの作成

Gemini曰く、イベントとは『「ユーザーが登録された」「商品が購入された」といった、アプリケーション内で発生した特定の出来事を表すクラスです。この出来事に関連する情報(どのユーザーが?どの商品を?など)を保持する役割を持ちます。』のことで、
リスナーとは『特定のイベントが発生するのを聞き耳を立てて待っているクラスです。イベントをキャッチすると、メール送信やログ記録など、定義された具体的な処理を実行します。』とのこと。

# 「ユーザーが登録された」イベント
php artisan make:event UserRegistered

# ↑のイベントをリッスンする「ログ記録」リスナー
php artisan make:listener WriteRegistrationLog

イベントの実装

app/Events/UserRegistered.php

<?php
namespace App\Events;

use App\Models\User; // Userモデルをインポート
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;

class UserRegistered
{
    use Dispatchable, SerializesModels;

    public $user; // publicプロパティでユーザー情報を保持

    /**
     * @param \App\Models\User $user
     */
    public function __construct(User $user)
    {
        $this->user = $user;
    }
}

リスナーの実装

app/Listeners/WriteRegistrationLog.php

<?php
namespace App\Listeners;

use App\Events\UserRegistered;
use Illuminate\Support\Facades\Log; // Logファサードをインポート

class WriteRegistrationLog
{
    public function __construct()
    {
        //
    }

    /**
     * イベントを処理
     *
     * @param \App\Events\UserRegistered $event
     */
    public function handle(UserRegistered $event): void
    {
        Log::info('新しいユーザーが登録されました。 UserID: ' . $event->user->id);
    }
}

EventServiceProviderへの登録

app/Providers/EventServiceProvider.php

<?php
namespace App\Providers;

use App\Events\UserRegistered;
use App\Listeners\WriteRegistrationLog;
// ... 他のuse文

class EventServiceProvider extends ServiceProvider
{
    /**
     * アプリケーションのイベントリスナーマッピング
     *
     * @var array
     */
    protected $listen = [

        // 以下3行を追加
        UserRegistered::class => [
            WriteRegistrationLog::class,
        ],
    ];

    // ...
}

イベントの発火

app/Http/Controllers/Auth/RegisterController.phpを作成し、

// ...
use App\Events\UserRegistered; // イベントをインポート

class RegisterController extends Controller
{
    // ...

    protected function create(array $data)
    {
        $user = User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => Hash::make($data['password']),
        ]);

        // ★★★ ここでイベントを発火! ★★★
        event(new UserRegistered($user));

        return $user;
    }
}

event()ヘルパー関数に、イベントクラスの新しいインスタンスを渡すだけでOKです。

あとはこのコントローラーを呼び出すルーティングを作成し、リクエストを行えばログが出力されます。

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?