Laravelでのイベント

イベントとリスナの作成

イベントクラスのみ作成

イベントクラスは通常、app/Eventsディレクトリに保存する。
イベントクラスのみを作成したい場合は、次のコマンドを実行する。

# php artisan make:event クラス名

リスナクラスのみ作成

リスナは通常、app/listenersディレクトリに保存する。
作成したイベントクラスに紐付けられるリスナを作成するには、次のコマンドを実行する。

# php artisan make:listener リスナ名 --event=イベントクラス名

イベントとリスナを同時に作成し、登録まで行う

イベントクラスとリスナクラスを同時に作成したい場合は、
app/Providers/EventServiceProvidersクラスにて次のように記述することで可能。

<?php

namespace App\Providers;

use Illuminate\Auth\Events\Registered;
use Illuminate\Auth\Listeners\SendEmailVerificationNotification;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Event;
use App\Events\TestEvent3;        # ここで場所を指定。
use App\Listeners\TestListener3;  # ここで場所を指定。

class EventServiceProvider extends ServiceProvider
{
    /**
     * The event to listener mappings for the application.
     *
     * @var array<class-string, array<int, class-string>>
     */
    protected $listen = [
        Registered::class => [
            SendEmailVerificationNotification::class,
        ],
        TestEvent2::class => [
            TestListener2::class,
        ],
        TestEvent3::class => [
            TestListener3::class,
        ],
    ];

    /**
     * Register any events for your application.
     */
    public function boot(): void
    {
        //
    }

    /**
     * Determine if events and listeners should be automatically discovered.
     */
    public function shouldDiscoverEvents(): bool
    {
        return false;
    }
}

EventServiceProvidersクラスが上記の状態で、次のコマンドを実行する。

# php artisan event:generate

すると、TestEvent2とTestListener2はapp/Providersディレクトリに作成され、
TestEvent3はapp/Eventsディレクトリに、TestListener3はapp/Listenersディレクトリにそれぞれ作成される。

登録されたイベントとリスナを確認

次のコマンドを実行することで、登録された全てのイベントとリスナのリストを表示できる。

# php artisan event:list

イベントを発火してみる

TestEvent3.php

<?php

namespace App\Events;

use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;

class TestEvent3
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    private string $tempStr;

    /**
     * Create a new event instance.
     */
    public function __construct(string $tempStr)
    {
        $this->tempStr = $tempStr;
    }

    public function getStr(): string
    {
        return $this->tempStr;
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return array<int, \Illuminate\Broadcasting\Channel>
     */
    public function broadcastOn(): array
    {
        return [
            new PrivateChannel('channel-name'),
        ];
    }
}

TestListener3.php

<?php

namespace App\Listeners;

use App\Events\TestEvent3;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;

class TestListener3
{
    /**
     * Create the event listener.
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     */
    public function handle(TestEvent3 $event): void
    {
        var_dump($event->getStr());
    }
}

動作確認

イベントとリスナが登録されていることを確認して、Tinkerで次のコードを実行する。

> use App\Events\TestEvent3;
> Event::dispatch(new TestEvent3('aiueo'));

すると、$strTempの内容がvar_dumpによって表示される。

コメント

タイトルとURLをコピーしました