Events

Introduction

Lumen's events provides a simple observer implementation, allowing you to subscribe and listen for events in your application. Event classes are typically stored in the app/Events directory, while their listeners are stored in app/Listeners.

Registering Events / Listeners

The EventServiceProvider included with your Lumen application provides a convenient place to register all event listeners. The provider is not loaded by default and must be enabled by un-commenting the following line in your bootstrap/app.php file:

  1. // $app->register(App\Providers\EventServiceProvider::class);

The listen property contains an array of all events (keys) and their listeners (values). Of course, you may add as many events to this array as your application requires. For example, let's add our PodcastWasPurchased event:

  1. /**
  2. * The event listener mappings for the application.
  3. *
  4. * @var array
  5. */
  6. protected $listen = [
  7. 'App\Events\PodcastWasPurchased' => [
  8. 'App\Listeners\EmailPurchaseConfirmation',
  9. ],
  10. ];

Defining Events

An event class is simply a data container which holds the information related to the event. For example, let's assume our generated PodcastWasPurchased event receives a Eloquent ORM object:

  1. <?php
  2. namespace App\Events;
  3. use App\Podcast;
  4. use App\Events\Event;
  5. use Illuminate\Queue\SerializesModels;
  6. class PodcastWasPurchased extends Event
  7. {
  8. use SerializesModels;
  9. public $podcast;
  10. /**
  11. * Create a new event instance.
  12. *
  13. * @param Podcast $podcast
  14. * @return void
  15. */
  16. public function __construct(Podcast $podcast)
  17. {
  18. $this->podcast = $podcast;
  19. }
  20. }

As you can see, this event class contains no special logic. It is simply a container for the Podcast object that was purchased. The SerializesModels trait used by the event will gracefully serialize any Eloquent models if the event object is serialized using PHP's serialize function.

Defining Listeners

Next, let's take a look at the listener for our example event. Event listeners receive the event instance in their handle method. Within the handle method, you may perform any logic necessary to respond to the event.

  1. <?php
  2. namespace App\Listeners;
  3. use App\Events\PodcastWasPurchased;
  4. use Illuminate\Queue\InteractsWithQueue;
  5. use Illuminate\Contracts\Queue\ShouldQueue;
  6. class EmailPurchaseConfirmation
  7. {
  8. /**
  9. * Create the event listener.
  10. *
  11. * @return void
  12. */
  13. public function __construct()
  14. {
  15. //
  16. }
  17. /**
  18. * Handle the event.
  19. *
  20. * @param PodcastWasPurchased $event
  21. * @return void
  22. */
  23. public function handle(PodcastWasPurchased $event)
  24. {
  25. // Access the podcast using $event->podcast...
  26. }
  27. }

Your event listeners may also type-hint any dependencies they need on their constructors. All event listeners are resolved via the Lumen service container, so dependencies will be injected automatically.

Stopping The Propagation Of An Event

Sometimes, you may wish to stop the propagation of an event to other listeners. You may do so using by returning false from your listener's handle method.

Queued Event Listeners

Need to queue an event listener? It couldn't be any easier. Simply add the ShouldQueue interface to the listener class. Listeners generated by the event:generate Artisan command already have this interface imported into the current namespace, so you can use it immediately:

  1. <?php
  2. namespace App\Listeners;
  3. use App\Events\PodcastWasPurchased;
  4. use Illuminate\Queue\InteractsWithQueue;
  5. use Illuminate\Contracts\Queue\ShouldQueue;
  6. class EmailPurchaseConfirmation implements ShouldQueue
  7. {
  8. //
  9. }

That's it! Now, when this listener is called for an event, it will be queued automatically by the event dispatcher using Lumen's queue system. If no exceptions are thrown when the listener is executed by the queue, the queued job will automatically be deleted after it has processed.

Manually Accessing The Queue

If you need to access the underlying queue job's delete and release methods manually, you may do so. The Illuminate\Queue\InteractsWithQueue trait, which is imported by default on generated listeners, gives you access to these methods:

  1. <?php
  2. namespace App\Listeners;
  3. use App\Events\PodcastWasPurchased;
  4. use Illuminate\Queue\InteractsWithQueue;
  5. use Illuminate\Contracts\Queue\ShouldQueue;
  6. class EmailPurchaseConfirmation implements ShouldQueue
  7. {
  8. use InteractsWithQueue;
  9. public function handle(PodcastWasPurchased $event)
  10. {
  11. if (true) {
  12. $this->release(30);
  13. }
  14. }
  15. }

Firing Events

To fire an event, you may use the Event facade, passing an instance of the event to the fire method. The fire method will dispatch the event to all of its registered listeners:

  1. <?php
  2. namespace App\Http\Controllers;
  3. use Event;
  4. use App\Podcast;
  5. use App\Events\PodcastWasPurchased;
  6. use App\Http\Controllers\Controller;
  7. class UserController extends Controller
  8. {
  9. /**
  10. * Show the profile for the given user.
  11. *
  12. * @param int $userId
  13. * @param int $podcastId
  14. * @return Response
  15. */
  16. public function purchasePodcast($userId, $podcastId)
  17. {
  18. $podcast = Podcast::findOrFail($podcastId);
  19. // Purchase podcast logic...
  20. Event::fire(new PodcastWasPurchased($podcast));
  21. }
  22. }

Alternatively, you may use the global event helper function to fire events:

  1. event(new PodcastWasPurchased($podcast));

Broadcasting Events

In many modern web applications, web sockets are used to implement real-time, live-updating user interfaces. When some data is updated on the server, a message is typically sent over a websocket connection to be handled by the client.

To assist you in building these types of applications, Lumen makes it easy to "broadcast" your events over a websocket connection. Broadcasting your Lumen events allows you to share the same event names between your server-side code and your client-side JavaScript framework.

Configuration

Lumen supports several broadcast drivers out of the box: Pusher, Redis, and a log driver for local development and debugging. A configuration example is included for each of these drivers. The BROADCAST_DRIVER configuration option may be used to set the default driver.

Broadcast Prerequisites

The following dependencies are needed for event broadcasting:

  • Pusher: pusher/pusher-php-server ~2.0
  • Redis: predis/predis ~1.0 illuminate/redis ~5.1

Queue Prerequisites

Before broadcasting events, you will also need to configure and run a queue listener. All event broadcasting is done via queued jobs so that the response time of your application is not seriously affected.

Marking Events For Broadcast

To inform Lumen that a given event should be broadcast, implement the Illuminate\Contracts\Broadcasting\ShouldBroadcast interface on the event class. The ShouldBroadcast interface requires you to implement a single method: broadcastOn. The broadcastOn method should return an array of "channel" names that the event should be broadcast on:

  1. <?php
  2. namespace App\Events;
  3. use App\User;
  4. use App\Events\Event;
  5. use Illuminate\Queue\SerializesModels;
  6. use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
  7. class ServerCreated extends Event implements ShouldBroadcast
  8. {
  9. use SerializesModels;
  10. public $user;
  11. /**
  12. * Create a new event instance.
  13. *
  14. * @return void
  15. */
  16. public function __construct(User $user)
  17. {
  18. $this->user = $user;
  19. }
  20. /**
  21. * Get the channels the event should be broadcast on.
  22. *
  23. * @return array
  24. */
  25. public function broadcastOn()
  26. {
  27. return ['user.'.$this->user->id];
  28. }
  29. }

Then, you only need to fire the event as you normally would. Once the event has been fired, a queued job will automatically broadcast the event over your specified broadcast driver.

Broadcast Data

When an event is broadcast, all of its public properties are automatically serialized and broadcast as the event's payload, allowing you to access any of its public data from your JavaScript application. So, for example, if your event has a single public $user property that contains an Eloquent model, the broadcast payload would be:

  1. {
  2. "user": {
  3. "id": 1,
  4. "name": "Jonathan Banks"
  5. ...
  6. }
  7. }

However, if you wish to have even more fine-grained control over your broadcast payload, you may add a broadcastWith method to your event. This method should return the array of data that you wish to broadcast with the event:

  1. /**
  2. * Get the data to broadcast.
  3. *
  4. * @return array
  5. */
  6. public function broadcastWith()
  7. {
  8. return ['user' => $this->user->id];
  9. }

Consuming Event Broadcasts

Pusher

You may conveniently consume events broadcast using the Pusher driver using Pusher's JavaScript SDK. For example, let's consume the App\Events\ServerCreated event from our previous examples:

  1. this.pusher = new Pusher('pusher-key');
  2. this.pusherChannel = this.pusher.subscribe('user.' + USER_ID);
  3. this.pusherChannel.bind('App\\Events\\ServerCreated', function(message) {
  4. console.log(message.user);
  5. });

Redis

If you are using the Redis broadcaster, you will need to write your own Redis pub/sub consumer to receive the messages and broadcast them using the websocket technology of your choice. For example, you may choose to use the popular Socket.io library which is written in Node.

Using the socket.io and ioredis Node libraries, you can quickly write an event broadcaster to publish all events that are broadcast by your Lumen application:

  1. var app = require('http').createServer(handler);
  2. var io = require('socket.io')(app);
  3. var Redis = require('ioredis');
  4. var redis = new Redis();
  5. app.listen(6001, function() {
  6. console.log('Server is running!');
  7. });
  8. function handler(req, res) {
  9. res.writeHead(200);
  10. res.end('');
  11. }
  12. io.on('connection', function(socket) {
  13. //
  14. });
  15. redis.psubscribe('*', function(err, count) {
  16. //
  17. });
  18. redis.on('pmessage', function(subscribed, channel, message) {
  19. message = JSON.parse(message);
  20. io.emit(channel + ':' + message.event, message.data);
  21. });

Event Subscribers

Event subscribers are classes that may subscribe to multiple events from within the class itself, allowing you to define several event handlers within a single class. Subscribers should define a subscribe method, which will be passed an event dispatcher instance:

  1. <?php
  2. namespace App\Listeners;
  3. class UserEventListener {
  4. /**
  5. * Handle user login events.
  6. */
  7. public function onUserLogin($event) {}
  8. /**
  9. * Handle user logout events.
  10. */
  11. public function onUserLogout($event) {}
  12. /**
  13. * Register the listeners for the subscriber.
  14. *
  15. * @param Illuminate\Events\Dispatcher $events
  16. * @return array
  17. */
  18. public function subscribe($events)
  19. {
  20. $events->listen(
  21. 'App\Events\UserLoggedIn',
  22. 'App\Listeners\[email protected]'
  23. );
  24. $events->listen(
  25. 'App\Events\UserLoggedOut',
  26. 'App\Listeners\[email protected]'
  27. );
  28. }
  29. }

Registering An Event Subscriber

Once the subscriber has been defined, it may be registered with the event dispatcher. You may register subscribers using the $subscribe property on the EventServiceProvider. For example, let's add the UserEventListener.

  1. <?php
  2. namespace App\Providers;
  3. use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
  4. class EventServiceProvider extends ServiceProvider
  5. {
  6. /**
  7. * The event listener mappings for the application.
  8. *
  9. * @var array
  10. */
  11. protected $listen = [
  12. //
  13. ];
  14. /**
  15. * The subscriber classes to register.
  16. *
  17. * @var array
  18. */
  19. protected $subscribe = [
  20. 'App\Listeners\UserEventListener',
  21. ];
  22. }