In-depth parsing of 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