LoginSignup
8
9

More than 5 years have passed since last update.

Laravel5.7でEventを利用してみる

Last updated at Posted at 2018-11-16

LaravelのEventを利用する機会があったので簡単にまとめてみます。

Eventの利用の流れは、

  • Eventを定義する
  • Eventに対応するListenerを定義する
  • Eventを仕込む(発火させる)

という感じ。

ここでは、特定のURLにアクセスがあったというEventを感知する機能を実装してみます。

  • Event→AccessDetection
  • Listener→AccessDetectionListener

という感じにします。

Eventの登録

Eventと対応するListenerはapp/Providers/EventServiceProvider.phpに登録する。

EventServiceProvider.php
<?php

namespace App\Providers;

use Illuminate\Support\Facades\Event;
use Illuminate\Auth\Events\Registered;
use Illuminate\Auth\Listeners\SendEmailVerificationNotification;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;

class EventServiceProvider extends ServiceProvider
{
    protected $listen = [
        Registered::class => [
            SendEmailVerificationNotification::class,
        ],
+        'App\Events\AccessDetection' => [
+            'App\Listeners\AccessDetectionListener',
+        ],
    ];

    public function boot()
    {
        parent::boot();

        //
    }
}

ファイルの生成

EventとListenerを登録しておけば、generateコマンドでファイルを生成してくれるようです。

php artisan event:generate

Event: AccessDetection.php

Eventはapp/Events以下に生成されます。
受け取ったパラメータを$param編集に保持するだけの記述をします。

AccessDetection.php
<?php

namespace App\Events;

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

class AccessDetection
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

+    public $param;

+    public function __construct($value)
    {
+        $this->param = $value;
    }

    public function broadcastOn()
    {
        return new PrivateChannel('channel-name');
    }
}

Listener: AccessDetectionLister.php

受け取った変数をそのままDump-Serverで表示します。

Dump-ServerはLaravel5.7で加わった機能です。

AccessDetectionListener.php
use App\Events\AccessDetection;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;

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

    public function handle(AccessDetection $event)
+    {
+        dump('Access Detected param=' . $event->param);
+    }
}

発火の設定

ここではeventというURLでアクセスしてきたときにAccessDetectionが発火するように定義します。
クロージャに記述しますが、普通はController内等で利用することになるかと思います。

use App\Events\AccessDetection;

Route::get('event', function(){
    event(new AccessDetection(str_random(10)));
    return 'hoge';
});

では、Laravelを起動ます。

php artisan serve

Dumpの内容が表示されるように別コンソールでDump-Serverを起動させます。

php artisan dump-server

eventにアクセスしてみます。
Dump-Serverのコンソールに下記のように表示されればOKです。

 ------------ -------------------------------------------
  date         Sun, 11 Nov 2018 23:41:46 +0000
  controller   "Closure"
  source       AccessDetectionListener.php on line 29
  file         app/Listeners/AccessDetectionListener.php
 ------------ -------------------------------------------

"Access Detected param=kujWmg4uAv"

簡単ですが、以上です。

参考

8
9
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
8
9