Browse Source

Lesson 32: Eventing.

Frederic G. MARAND 6 years ago
parent
commit
173bbb8dde

+ 36 - 0
app/Events/ThreadCreated.php

@@ -0,0 +1,36 @@
+<?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 ThreadCreated
+{
+    use Dispatchable, InteractsWithSockets, SerializesModels;
+
+    public $thread;
+
+    /**
+     * Create a new event instance.
+     */
+    public function __construct($thread)
+    {
+        $this->thread = $thread;
+    }
+
+    /**
+     * Get the channels the event should broadcast on.
+     *
+     * @return Channel|array
+     */
+    public function broadcastOn()
+    {
+        return new PrivateChannel('channel-name');
+    }
+}

+ 31 - 0
app/Listeners/CheckForSpam.php

@@ -0,0 +1,31 @@
+<?php
+
+namespace App\Listeners;
+
+use App\Events\ThreadCreated;
+use Illuminate\Queue\InteractsWithQueue;
+use Illuminate\Contracts\Queue\ShouldQueue;
+
+class CheckForSpam implements ShouldQueue
+{
+    /**
+     * Create the event listener.
+     *
+     * @return void
+     */
+    public function __construct()
+    {
+        //
+    }
+
+    /**
+     * Handle the event.
+     *
+     * @param  ThreadCreated  $event
+     * @return void
+     */
+    public function handle(ThreadCreated $event)
+    {
+        var_dump('Checking for spam');
+    }
+}

+ 28 - 0
app/Listeners/NotifySubscribers.php

@@ -0,0 +1,28 @@
+<?php
+
+namespace App\Listeners;
+
+use App\Events\ThreadCreated;
+use Illuminate\Queue\InteractsWithQueue;
+use Illuminate\Contracts\Queue\ShouldQueue;
+
+class NotifySubscribers
+{
+    /**
+     * Create the event listener.
+     */
+    public function __construct()
+    {
+        //
+    }
+
+    /**
+     * Handle the event.
+     *
+     * @param  ThreadCreated  $event
+     */
+    public function handle(ThreadCreated $event)
+    {
+        var_dump($event->thread['name'] . ' was published to the forum');
+    }
+}

+ 6 - 2
app/Providers/EventServiceProvider.php

@@ -2,6 +2,9 @@
 
 namespace App\Providers;
 
+use App\Events\ThreadCreated;
+use App\Listeners\CheckForSpam;
+use App\Listeners\NotifySubscribers;
 use Illuminate\Support\Facades\Event;
 use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
 
@@ -13,8 +16,9 @@ class EventServiceProvider extends ServiceProvider
      * @var array
      */
     protected $listen = [
-        'App\Events\Event' => [
-            'App\Listeners\EventListener',
+        ThreadCreated::class => [
+            NotifySubscribers::class,
+            CheckForSpam::class,
         ],
     ];