Parsing of event events operations in PHP's Laravel framework

Source: Internet
Author: User
This article mainly introduces the Laravel framework of PHP event event operation, which focuses on the new Laravel 5.1 added event broadcast function, the need for friends can refer to the following

Sometimes when we simply look at the Laravel manual there will be some doubts, such as the authorization and events under the system service, what are the application scenarios of these functional services, in fact, if you have not experienced a certain development experience have these doubts is very normal things, But when we think more about our work, we can see that sometimes we've seen these services in fact. Here's a very simple example of event and event monitoring, and you'll find out.

This example is about the implementation of the article browsing number, when the user view the article when the number of articles will be increased by 1, the user to view the article is an event, with the event, you need an event listener, to listen to the event after the execution of the corresponding operation (article views plus 1), in fact, this monitoring mechanism in Laravel is implemented through the observer pattern.

Registering events and listeners
First we need to register the event listener mapping relationship in the eventserviceprovider.php in the app/providers/directory, as follows:

protected $listen = [    ' App\events\blogview ' = [      ' App\listeners\blogviewlistener ',    ],  ];

Then execute the following command under the project root directory

PHP Artisan Event:generate

Once this command is complete, blogview.php and blogviewlistener.php files are automatically generated in the App/events and App/listensers directories, respectively.

Defining events

<?phpnamespace app\events;use app\events\event;use app\post;use illuminate\queue\serializesmodels;use Illuminate \contracts\broadcasting\shouldbroadcast;class Blogview extends event{use  serializesmodels;  /**   * Create A new event instance.   *   * @return void   *  /Public Function __construct (Post $post)  {    $this->post = $post;  }  /**   * Get The channels the event should is broadcast on.   *   * @return Array   *  /Public Function Broadcaston ()  {    return [];}  }

Actually seeing these you will find that the event class just injects a post instance, and does not contain extraneous logic.

Defining listeners
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 events in the handle method. Within the handle method, you can execute any required logic in response to the event, and our code is implemented as follows:

<?phpnamespace app\listeners;use app\events\blogview;use illuminate\queue\interactswithqueue;use Illuminate\  Contracts\queue\shouldqueue;use illuminate\session\store;class blogviewlistener{protected $session;   /** * Create the event listener.  * * @return void */Public function __construct (Store $session) {$this->session = $session;   }/** * Handle the event.      * * @param blogview $event * @return void */Public function handle (Blogview $event) {$post = $event->post; First determine if you have viewed if (! $this->hasviewedblog ($post)) {//Save to database $post->view_cache = $post->view_ca      Che + 1;       $post->save ();    After you have seen it, save it to the Session $this->storeviewedblog ($post);  }} protected function Hasviewedblog ($post) {return array_key_exists ($post->id, $this->getviewedblogs ());  } protected function Getviewedblogs () {return $this->session->get (' viewed_blogs ', []); } protected function Storeviewedblog ($post) {   $key = ' viewed_blogs. '    $post->id;  $this->session->put ($key, Time ()); }}

Some logic has also been explained in the comments.

Triggering events
After the event and event monitoring is complete, all we have to do is implement the entire listener, that is, the fire method that triggers the user to open the article event, which we use and event provides, as follows:

<?phpnamespace app\http\controllers;use illuminate\http\request;use app\post;use Illuminate\Support\Facades\ Event;use app\http\requests;use app\events\blogview;use App\http\controllers\controller;class BlogController Extends controller{public    function Showpost ($slug)  {    $post = Post::whereslug ($slug)->firstorfail ();    Event::fire (New Blogview ($post));    Return view (' Home.blog.content ')->withpost ($post);}  }

Now open the page found in the database of the ' View_cache has been normal add 1, so the whole is done.

Event broadcast
Brief introduction:
Laravel 5.1 In the new event broadcast function, the role of the server triggered by the event through the WebSocket service notify the client, that is, the browser, the client JS according to the received events, make corresponding actions. This article demonstrates the process of an event broadcast with simple code.

Depend on:

    • Redis

    • Nodejs, Socket.io

    • Laravel 5.1

Configuration:

    • In config/broadcasting.php, the following configuration ' default ' = env (' Broadcast_driver ', ' Redis '), using Redis as a means of communication between PHP and JS.

    • Configure Redis connections in the config/database.php.

Define an event that is broadcast:
Depending on the description of the Laravel documentation, to enable the event to be broadcast, you must have the event class implement a Illuminate\contracts\broadcasting\shouldbroadcast interface and implement a method Broadcaston. Broadcaston returns an array that contains the channel (channel) to which the event was sent. As follows:

namespace App\events;use app\events\event;use Illuminate\queue\serializesmodels;use illuminate\contracts\ Broadcasting\shouldbroadcast;class Someevent extends Event implements shouldbroadcast{use  serializesmodels;  Public $user _id;  /**   * Create A new event instance.   *   * @return void   *  /Public Function __construct ($user _id)  {    $this->user_id = $user _id;  }  /**   * Get The channels the event should is broadcast on.   *   * @return Array   *  /Public Function Broadcaston ()  {    return [' Test-channel '];}  }

Data to be broadcast:
By default, all public properties in an event are serialized and broadcast. In the above example, $user_id is the attribute. You can also use the Broadcastwith method to clearly indicate what data to broadcast. For example:

Public Function Broadcastwith () {  return [' user_id ' = ' = $this->user_id];}

Redis and WebSocket servers:
Need to start a Redis, the event broadcast is mainly dependent on the Redis sub/pub feature, you can see the Redis document
Need to start a websocket server to communicate with client, we recommend using Socket.io, the code is as follows:

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

It is important to note that the definition of the Redis.on method, after receiving the message, sends an event to the client, the event name is Channel + ': ' + message.event.

Client code:
Client We also use Socket.io, as a test, the code is as simple as possible, just print one of the received data. As follows:

var socket = io (' http://localhost:6001 '); Socket.on (' Connection ', function (data) {  console.log (data);}); Socket.on (' Test-channel:app\\events\\someevent ', function (message) {  console.log (message);}); Console.log (socket);

Server-Triggered events:
An event trigger can be defined directly in the router. As follows:

Route::get ('/event ', function () {  event::fire (new \app\events\someevent (3));  Return "Hello World";});

Test:

    • Start Redis

    • Start WebSocket

    • Open the page with the client code and you can see that the WebSocket is connected successfully.

    • Trigger an event to open another page localhost/event.

At this point, you can see that the first page of the console printed out Object{user_id:3}, indicating that the broadcast was successful.

The above is the whole content of this article, I hope that everyone's learning has helped, more relevant content please pay attention to topic.alibabacloud.com!

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.