Table of Contents
深入解析PHP的Laravel框架中的event事件操作,laravelevent
您可能感兴趣的文章:
Home php教程 php手册 深入解析PHP的Laravel框架中的event事件操作,laravelevent

深入解析PHP的Laravel框架中的event事件操作,laravelevent

Jun 13, 2016 am 08:43 AM
laravel php

深入解析PHP的Laravel框架中的event事件操作,laravelevent

 有时候当我们单纯的看 Laravel 手册的时候会有一些疑惑,比如说系统服务下的授权和事件,这些功能服务的应用场景是什么,其实如果没有经历过一定的开发经验有这些疑惑是很正常的事情,但是当我们在工作中多加思考会发现有时候这些服务其实我们一直都见过。下面就事件、事件监听举一个很简单的例子你就会发现。

​ 这个例子是关于文章的浏览数的实现,当用户查看文章的时候文章的浏览数会增加1,用户查看文章就是一个事件,有了事件,就需要一个事件监听器,对监听的事件发生后执行相应的操作(文章浏览数加1),其实这种监听机制在 Laravel 中是通过观察者模式实现的.

注册事件以及监听器
首先我们需要在 app/Providers/目录下的EventServiceProvider.php中注册事件监听器映射关系,如下:

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

然后项目根目录下执行如下命令

php artisan event:generate
Copy after login

该命令完成后,会分别自动在 app/Events和app/Listensers目录下生成 BlogView.php和BlogViewListener.php文件。

定义事件

<&#63;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 [];
  }
}

Copy after login

其实看到这些你会发现该事件类只是注入了一个 Post实例罢了,并没有包含多余的逻辑。

定义监听器
事件监听器在handle方法中接收事件实例,event:generate命令将会自动在handle方法中导入合适的事件类和类型提示事件。在handle方法内,你可以执行任何需要的逻辑以响应事件,我们的代码实现如下:

<&#63;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());
  }

}

Copy after login

注释中也已经说明了一些逻辑。

触发事件
事件和事件监听完成后,我们要做的就是实现整个监听,即触发用户打开文章事件在此我们使用和 Event提供的 fire方法,如下:

<&#63;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);
  }

}

Copy after login

现在打开页面发现数据库中的`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'];
  }
}

Copy after login

被广播的数据:
默认情况下,Event中的所有public属性都会被序列化后广播。上面的例子中就是$user_id这个属性。你也可以使用broadcastWith这个方法,明确的指出要广播什么数据。例如:

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

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);
});

Copy after login

这里需要注意的是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);
Copy after login

服务器触发事件:
直接在router中定义个事件触发即可。如下:

Route::get('/event', function(){
  Event::fire(new \App\Events\SomeEvent(3));
  return "hello world";
});
Copy after login

测试:

  • 启动redis
  • 启动websocket
  • 打开带有客户端代码的页面,可以看到websocket已经连接成功。
  • 触发事件,打开另一个页面 localhost/event。

这时就可以发现,第一个页面的console中打印出了Object{user_id: 3},说明广播成功。

您可能感兴趣的文章:

  • PHP的Laravel框架结合MySQL与Redis数据库的使用部署
  • PHP的Laravel框架中使用消息队列queue及异步队列的方法
  • 详解PHP的Laravel框架中Eloquent对象关系映射使用
  • PHP框架Laravel学习心得体会
  • 全面解读PHP的人气开发框架Laravel
  • Nginx中运行PHP框架Laravel的配置文件分享
  • PHP IDE PHPStorm配置支持友好Laravel代码提示方法
  • 使用 PHPStorm 开发 Laravel
  • PHP开发框架laravel安装与配置教程
  • PHP框架Laravel的小技巧两则
  • PHP的Laravel框架中使用AdminLTE模板来编写网站后台
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

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's Current Status: A Look at Web Development Trends PHP's Current Status: A Look at Web Development Trends Apr 13, 2025 am 12:20 AM

PHP remains important in modern web development, especially in content management and e-commerce platforms. 1) PHP has a rich ecosystem and strong framework support, such as Laravel and Symfony. 2) Performance optimization can be achieved through OPcache and Nginx. 3) PHP8.0 introduces JIT compiler to improve performance. 4) Cloud-native applications are deployed through Docker and Kubernetes to improve flexibility and scalability.

PHP's Purpose: Building Dynamic Websites PHP's Purpose: Building Dynamic Websites Apr 15, 2025 am 12:18 AM

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.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

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.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

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 and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

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.

Why Use PHP? Advantages and Benefits Explained Why Use PHP? Advantages and Benefits Explained Apr 16, 2025 am 12:16 AM

The core benefits of PHP include ease of learning, strong web development support, rich libraries and frameworks, high performance and scalability, cross-platform compatibility, and cost-effectiveness. 1) Easy to learn and use, suitable for beginners; 2) Good integration with web servers and supports multiple databases; 3) Have powerful frameworks such as Laravel; 4) High performance can be achieved through optimization; 5) Support multiple operating systems; 6) Open source to reduce development costs.

See all articles