这篇文章主要介绍了PHP的Laravel框架中的event事件操作,其中重点讲解了Laravel 5.1之中新加入了事件广播的功能,需要的朋友可以参考下
有时候当我们单纯的看 Laravel 手册的时候会有一些疑惑,比如说系统服务下的授权和事件,这些功能服务的应用场景是什么,其实如果没有经历过一定的开发经验有这些疑惑是很正常的事情,但是当我们在工作中多加思考会发现有时候这些服务其实我们一直都见过。下面就事件、事件监听举一个很简单的例子你就会发现。
这个例子是关于文章的浏览数的实现,当用户查看文章的时候文章的浏览数会增加1,用户查看文章就是一个事件,有了事件,就需要一个事件监听器,对监听的事件发生后执行相应的操作(文章浏览数加1),其实这种监听机制在 Laravel 中是通过观察者模式实现的.
注册事件以及监听器
首先我们需要在 app/Providers/目录下的EventServiceProvider.php中注册事件监听器映射关系,如下:
protected $listen = [ 'App\Events\BlogView' => [ 'App\Listeners\BlogViewListener', ], ];
然后项目根目录下执行如下命令
php artisan event:generate
该命令完成后,会分别自动在 app/Events和app/Listensers目录下生成 BlogView.php和BlogViewListener.php文件。
定义事件
<?php namespace 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 []; } }
其实看到这些你会发现该事件类只是注入了一个 Post实例罢了,并没有包含多余的逻辑。
定义监听器
事件监听器在handle方法中接收事件实例,event:generate命令将会自动在handle方法中导入合适的事件类和类型提示事件。在handle方法内,你可以执行任何需要的逻辑以响应事件,我们的代码实现如下:
<?php namespace 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; //先进行判断是否已经查看过 if (!$this->hasViewedBlog($post)) { //保存到数据库 $post->view_cache = $post->view_cache + 1; $post->save(); //看过之后将保存到 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()); } }
注释中也已经说明了一些逻辑。
触发事件
事件和事件监听完成后,我们要做的就是实现整个监听,即触发用户打开文章事件在此我们使用和 Event提供的 fire方法,如下:
<?php namespace 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); } }
现在打开页面发现数据库中的`view_cache已经正常加1了,这样整个就完成了。
事件广播
简介:
Laravel 5.1 之中新加入了事件广播的功能,作用是把服务器中触发的事件通过websocket服务通知客户端,也就是浏览器,客户端js根据接受到的事件,做出相应动作。本文会用简单的代码展示一个事件广播的过程。
依赖:
redis
nodejs, socket.io
laravel 5.1
配置:
config/broadcasting.php中,如下配置'default' => env('BROADCAST_DRIVER', 'redis'),,使用redis作为php和js的通信方式。
config/database.php中配置redis的连接。
定义一个被广播的事件:
根据Laravel文档的说明,想让事件被广播,必须让Event类实现一个Illuminate\Contracts\Broadcasting\ShouldBroadcast接口,并且实现一个方法broadcastOn。broadcastOn返回一个数组,包含了事件发送到的channel(频道)。如下:
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']; } }
被广播的数据:
默认情况下,Event中的所有public属性都会被序列化后广播。上面的例子中就是$user_id这个属性。你也可以使用broadcastWith这个方法,明确的指出要广播什么数据。例如:
public function broadcastWith() { return ['user_id' => $this->user_id]; }
Redis和Websocket服务器:
需要启动一个Redis,事件广播主要依赖的就是redis的sub/pub功能,具体可以看redis文档
需要启动一个websocket服务器来和client通信,建议使用socket.io,代码如下:
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); });
这里需要注意的是redis.on方法的定义,接收到消息后,给client发送一个事件,事件名称为channel + ':' + message.event。
客户端代码:
客户端我们也使用socket.io,作为测试,代码尽量简化,仅仅打印一个接受到的数据即可。如下:
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);
服务器触发事件:
直接在router中定义个事件触发即可。如下:
Route::get('/event', function(){ Event::fire(new \App\Events\SomeEvent(3)); return "hello world"; });
测试:
启动redis
启动websocket
打开带有客户端代码的页面,可以看到websocket已经连接成功。
触发事件,打开另一个页面 localhost/event。
这时就可以发现,第一个页面的console中打印出了Object{user_id: 3},说明广播成功。
The above is the entire content of this article. I hope it will be helpful to everyone's study. For more related content, please pay attention to the PHP Chinese website!
Related recommendations:
Passed Laravel implements user registration and login
Learning to transfer array to view in Laravel5 framework
The above is the detailed content of Analysis of event operation in PHP's Laravel framework. For more information, please follow other related articles on the PHP Chinese website!

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

Using preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP makes it easy to create interactive web content. 1) Dynamically generate content by embedding HTML and display it in real time based on user input or database data. 2) Process form submission and generate dynamic output to ensure that htmlspecialchars is used to prevent XSS. 3) Use MySQL to create a user registration system, and use password_hash and preprocessing statements to enhance security. Mastering these techniques will improve the efficiency of web development.

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Chinese version
Chinese version, very easy to use

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version
Useful JavaScript development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment