In-depth parsing of event operations in the Laravel framework of PHP, laravelevent_PHP tutorial

Source: Internet
Author: User
In-depth analysis of event operations in the Laravel framework of PHP, laravelevent. In-depth analysis of event operations in the Laravel framework of PHP, laravelevent sometimes has some doubts when we simply read the Laravel manual, for example, authorization and events under the system service are deeply parsed into event operations in the Laravel framework of PHP, laravelevent

Sometimes, when we simply look at the Laravel manual, there may be some questions, such as the authorization and events under the system service, what are the application scenarios of these functional services, in fact, it is normal to have doubts if we have never experienced development experience, but when we think more at work, we will find that sometimes we have seen these services all the time. The following is a simple example of event and event monitoring.

This example is about the implementation of the number of articles. when a user views an article, the number of articles browsed increases by 1. when a user views an article, it is an event with an event, an event listener is required to perform corresponding operations on the monitored events (article browsing Shujia 1). In fact, this listener mechanism is implemented in Laravel through the observer mode.

Register events and listeners
First, register the event listener ing relationship in EventServiceProvider. php under the app/Providers/directory, as shown below:

protected $listen = [    'App\Events\BlogView' => [      'App\Listeners\BlogViewListener',    ],  ];

Run the following command in the project Root Directory:

php artisan event:generate

After the command is completed, the BlogView. php and BlogViewListener. php files are automatically generated in the app/Events and app/Listensers directories.

Define 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 be broadcast on.   *   * @return array   */  public function broadcastOn()  {    return [];  }}

In fact, when you see this, you will find that the event class only injects a Post instance and does not contain any redundant logic.

Define listener
The event listener receives event instances in the handle method. the event: generate command automatically imports the appropriate event classes and types in the handle method. In the handle method, you can execute any required logic to respond to events. our code implementation is 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; // you can first determine whether you have checked if (! $ This-> hasViewedBlog ($ post) {// save to database $ post-> view_cache = $ post-> view_cache + 1; $ post-> save (); // save it to 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 is also described in the annotations.

Trigger Event
After the Event and Event listening are complete, all we need to do is to implement the whole listening, that is, to trigger the user to open the article Event. here we use the fire method provided by the Event 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);  }}

Open the page and you will find that the 'view _ cache in the database has been properly added with 1, so the whole process is complete.

Event broadcast
Introduction:
Laravel 5.1 adds the event broadcast function to notify the client of events triggered on the server through the websocket service, that is, the browser. based on the received events, the client js, make corresponding actions. This article uses simple code to demonstrate an event broadcast process.

Dependency:

  • Redis
  • Nodejs, socket. io
  • Laravel 5.1

Configuration:

  • In config/broadcasting. php, 'default' => env ('broadcast _ DRIVER ', 'redis') is configured as follows. redis is used as the communication mode between php and js.
  • Configure the redis connection in config/database. php.

Define a broadcast event:
According to the instructions in Laravel, to broadcast an Event, you must enable the Event class to implement an Illuminate \ Contracts \ Broadcasting \ ShouldBroadcast interface and a method of broadcastOn. BroadcastOn returns an array containing the channel to which the event is 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 be broadcast on.   *   * @return array   */  public function broadcastOn()  {    return ['test-channel'];  }}

Broadcasted data:
By default, all the public attributes in the Event are serialized and then broadcast. In the preceding example, the $ user_id attribute is used. You can also use the broadcastWith method to clearly specify what data to broadcast. For example:

public function broadcastWith(){  return ['user_id' => $this->user_id];}

Redis and Websocket servers:
You need to start a Redis instance. event broadcast mainly depends on redis's sub/pub function. for details, see the redis documentation.
To enable a websocket server to communicate with the 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(200);  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);});

Note the definition of the redis. on Method. after receiving a message, send an event to the client named channel + ':' + message. event.

Client code:
The client also uses socket. io for testing. the code is simplified as much as possible and only one accepted data is printed. 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 trigger event:
Define an event trigger in the router directly. 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 has been successfully connected.
  • Trigger event to open localhost/event on another page.

At this time, we can find that the first page of the console prints the Object {user_id: 3}, indicating that the broadcast is successful.

Articles you may be interested in:
  • The Laravel framework of PHP is combined with the use and deployment of MySQL and Redis databases.
  • Methods for using message queue and asynchronous queue in the Laravel framework of PHP
  • Describes how to use Eloquent object ing in the Laravel framework of PHP.
  • PHP framework Laravel learning experience
  • A comprehensive explanation of the popular PHP development framework Laravel
  • Share the configuration file for running the PHP framework Laravel in Nginx
  • Php ide PHPStorm supports friendly Laravel code prompts
  • Use PHPStorm to develop Laravel
  • PHP development framework laravel installation and configuration tutorial
  • Two tips for Laravel PHP Framework
  • Use the AdminLTE template in the Laravel framework of PHP to compile the website background

Sometimes, when we simply look at the Laravel manual, there may be some questions, such as the authorization and tasks in the system service...

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.