[Laravel 5.2 Documentation] service--Events

Source: Internet
Author: User

1. Introduction

The Laravel event provides a simple observer pattern implementation that allows you to subscribe and listen to events in your app. Event classes are usually stored in the App/events directory, and the listener is stored in app/listeners.

2. Registering Events/Listeners

Laravel's own Eventserviceprovider provides a convenient location for event registration. The Listen property contains an array of events (keys) and corresponding listeners (values). If the application requires, you can add multiple events to the array. For example, let's add the Podcastwaspurchased event:

/** * Event Listener Map * * @var array */protected $listen = [    ' app\events\podcastwaspurchased ' + = [        ' App\listeners\email Purchaseconfirmation ',    ],];

2.1 Generating Event/Listener classes

Of course, it is cumbersome to manually create files for each event and listener, and instead, we can simply add listeners and events to Eventserviceprovider and then use the Event:generate command. This command will generate all the events and listeners listed in the Eventserviceprovider. Of course, existing events and listeners will not be created:

PHP Artisan Event:generate

2.2 Registering events manually

In general we need to register the event to the $listen array of Eventserviceprovider, and we can also use event façade or illuminate\contracts\events\ The specific implementation class of the dispatcher contract registers the event manually as an event dispatcher:

/** * Register Any other events for your application. * * @param  \illuminate\contracts\events\dispatcher  $events * @return void */public function boot ( Dispatchercontract $events) {    parent::boot ($events);    $events->listen (' Event.name ', function ($foo, $bar) {        //    });}

Using wildcard characters as event listeners

You can also use the wildcard * to register listeners, allowing you to capture multiple events from the same listener. The wildcard listener receives an array of event data as parameters:

$events->listen (' event.* ', function (array $data) {    //});

3. Defining Events

The event class is a simple data container that handles event-related events, for example, assuming that the podcastwaspurchased event we generate receives a eloquent ORM object:

 
  Podcast = $podcast;    }}

As you can see, the event class does not contain any specific logic, just a container to store the podcast object that was purchased, and if the event object is serialized, the serializesmodelstrait used by the event will serialize all of the objects using PHP's Serialize function. Eloquent model.

4. Define the Listener

Next, let's take a look at our sample event listener, the event listener receives the event instance in the handle method, and the Event:generate command automatically imports the appropriate event class and type hint event in the handle method. Within the handle method, you can execute any required logic in response to an event.

 
  Podcast ...    }}

Your event listener can also prompt any required dependencies in the constructor, and all event listeners are parsed through the service container, so the dependency is automatically injected:

Use Illuminate\contracts\mail\mailer;public function __construct (Mailer $mailer) {    $this->mailer = $mailer;}

Stop events continue to propagate down

Sometimes you want the stop event to be propagated to other listeners, and you can do so by returning false from the listener's handle method.

Event Listener Queue

Need to put event listeners in the queue? Nothing is simpler than this, just let the listener class implement the Shouldqueue interface, the listener class generated by the Artisan command event:generate has imported the interface into the current namespace, all of which you can immediately use:

     

It is that simple, when the listener is called by the event, it will use the queue system of Laravel to automatically queue through the queue dispatcher. If no exception is thrown when the listener is executed through the queue, the queue task is automatically deleted after execution is complete.

Manual access to queues

If you need to manually access the delete and release methods of the underlying queue task, the default imported illuminate\queue\interactswithqueuetrait in the generated listener provides access to both methods:

 
   Release (+);}}}    

5. Triggering Events

To trigger an event, you can use the event façade to pass an event instance to the fire method, which distributes the event to all listeners:

      

In addition, you can use the Global helper function event to trigger an event:

Event (New podcastwaspurchased ($podcast));

6. Broadcast Events

In many modern Web applications, Web sockets are used to implement a user interface for real-time updates. When some data is updated on the server, usually a message is sent through the WebSocket connection to the client for processing.

To help you build such an application, Laravel makes it easy to connect broadcast events via WebSocket. The broadcast Laravel event allows you to share the same event name between the server and the client JavaScript framework.

6.1 Configuration

All event broadcast configuration options are stored in the config/broadcasting.php configuration file. Laravel supports multiple broadcast drivers: Pusher, Redis, and a log driver that serves local development and debugging. Each driver has a sample configuration.

Broadcast Readiness Knowledge

An event broadcast requires the following two dependencies:

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

Queue Prep Knowledge

Before you begin to introduce broadcast events, you need to configure and run a queue listener. All event broadcasts are completed through a queue task so that the application's response time is not affected.

6.2 Marking events as broadcast

To tell Laravel that a given event should be broadcast, the Illuminate\contracts\broadcasting\shouldbroadcast interface needs to be implemented on the event class. The Shouldbroadcast interface requires you to implement a method: Broadcaston. The method should return an array of event broadcast "channel" names:

 
    user = $user;    }    /**     * Get event Broadcast Channel     *     * @return Array     *    /Public Function Broadcaston ()    {        return [' User. '. $this->user->id];    }}

Then, you only need to trigger the event as normal, and after the event is triggered, a queue task will automatically broadcast the event by specifying the broadcast driver.

6.3 Broadcast Data

If an event is broadcast, all of its public properties are automatically serialized and broadcast according to the event payload, allowing you to access all the public data from JavaScript, so, for example, if your event has a separate $user attribute that contains the eloquent model, The broadcast payload is defined as follows:

{    "user": {        "id": 1,        "name": "Jonathan Banks"        ...    }}

However, if you want more granular control over the broadcast payload, you can add the Broadcastwith method to the event, which should return the array data that you want to broadcast through the event:

/** * GET Broadcast data * * @return array */public function Broadcastwith () {    return [' user ' = $this->user->id];}

6.4 Custom Event Broadcasts

Custom event Name

By default, the broadcast event name is the event class name, so if the class name of the event is app\events\servercreated, the corresponding broadcast event name is app\events\servercreated, which you can pass through the event class Broadcastas method Custom Broadcast event name:

/** * Get Broadcast event name * * @return string */public function Broadcastas () {    return ' app.server-created ';}

Custom queues

By default, each broadcast event is in the default queue in the default queue connection defined in profile queue.php, and you can customize the queue name of the broadcast event through the Onqueue method of the event class. This method returns the name of the queue you expect to use:

/** * Set the name of the queue where the event is located * * @return string */public function Onqueue () {    return ' your-queue-name ';}

6.5 Consumer Event Broadcast

Pusher

You can easily use pusher to drive consumer event broadcasts via the pusher JavaScript SDK. For example, let's consume the App\events\servercreated event from the previous example:

This.pusher = new Pusher (' Pusher-key '); this.pusherchannel = This.pusher.subscribe (' user. ' + user_id); This.pusherChannel.bind (' app\\events\\servercreated ', function (message) {    console.log (message.user);});

Redis

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

Using Node library Socket.io and Ioredis, you can quickly write event broadcasts to publish all broadcast events:

var app = require (' http '). Createserver (handler); var io = require (' Socket.io ') (app); var Redis = require (' Ioredis '); var Redis = new Redis (); App.listen (6001, function () {    Console.log (' Server is running! ');}); function handler (req, res) {    res.writehead (+);    Res.end (');} Io.on (' Connection ', function (socket) {    //}), Redis.psubscribe (' * ', function (err, count) {    //}); Redis.on (' Pmessage ', function (subscribed, channel, message) {    message = json.parse (message);    Io.emit (Channel + ': ' + message.event, message.data);});

7. Event subscribers

Event subscribers are classes that subscribe to multiple events in the class itself, allowing you to define some event handlers in a single class. Subscribers should define a subscribe method in which an event dispatcher instance is passed in:

 
    Listen (            ' App\events\userloggedin ',            ' App\listeners\usereventlistener@onuserlogin '        );        $events->listen (            ' app\events\userloggedout ',            ' app\listeners\usereventlistener@onuserlogout '        );}    }

Register an Event subscriber

Once a subscriber is defined, it can be registered via the event dispatcher, and you can use the $subcribe property on Eventserviceprovider to register subscribers. For example, let's add Usereventlistener:

!--? phpnamespace App\providers;use Illuminate\contracts\events\dispatcher as Dispatchercontract;use Illuminate\foundation\support\providers\eventserviceprovider as ServiceProvider;class Eventserviceprovider extends serviceprovider{/** * Event Listener Map Array * * @var array */protected $listen =    [        //    ]; /** * Subscriber to register * * @var array */protected $subscribe = [' App\listeners\usereventlistener ',] ;} 
  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.