Table of Contents
生成一个事件类
定义监听器
分发和触发事件
队列异步处理
Home Backend Development PHP Tutorial Summary of Laravel event system usage

Summary of Laravel event system usage

Jul 06, 2018 pm 04:28 PM
laravel php event listening

这篇文章主要介绍了关于Laravel 事件系统用法的总结,有着一定的参考价值,现在分享给大家,有需要的朋友可以参考一下

Laravel 的事件提供了一个简单的观察者实现,能够订阅和监听应用中发生的各种事件。事件类保存在 app/Events 目录中,而这些事件的的监听器则被保存在 app/Listeners 目录下。这些目录只有当你使用 Artisan 命令来生成事件和监听器时才会被自动创建。

事件机制是一种很好的应用解耦方式,因为一个事件可以拥有多个互不依赖的监听器。例如,如果你希望每次订单发货时向用户发送一个 Slack 通知。你可以简单地发起一个 OrderShipped 事件,让监听器接收之后转化成一个 Slack 通知,这样你就可以不用把订单的业务代码跟 Slack 通知的代码耦合在一起了。

生成一个事件类

比如通过 artisan 命令生成一个 UserLogin 事件:

php artisan make:event UserLogin
Copy after login

在 app/Events 中就会自动生成一个 UserLogin.php 文件,内容不多,如下:

<?php
 
namespace App\Events;
 
use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
 
class UserLogin
{
    use InteractsWithSockets, SerializesModels;
 
    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }
 
    /**
     * Get the channels the event should broadcast on.
     *
     * @return Channel|array
     */
    public function broadcastOn()
    {
        return new PrivateChannel(&#39;channel-name&#39;);
    }
}
Copy after login

定义监听器

一个事件可以被一个或多个监听器监听,也就是观察者模式,我们可以定义多个监听器,当这个事件发生,执行一系列逻辑。

在 EventServiceProvider 的 $listen 中可以定义事件和监听器,如下:

protected $listen = [
    &#39;App\Events\UserLogin&#39; => [
        &#39;App\Lisenter\DoSomething1&#39;,
        &#39;App\Lisenter\Dosomething2&#39;,
    ],
];
Copy after login

然后执行 artisan 命令,就可以自动在 app/Lisenter 目录生成监听器。

php artisan make:event generate
Copy after login

可以看到 app/Lisenter 目录多了 DoSomething1.php 和 DoSomething2.php 两个文件,我们看看其中一个内容:

<?php
 
namespace App\Lisenter;
 
use App\Events\UserLogin;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
 
class DoSomething1
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }
 
    /**
     * Handle the event.
     *
     * @param  UserLogin  $event
     * @return void
     */
    public function handle(UserLogin $event)
    {
        info(&#39;do something1&#39;);
    }
}
Copy after login

在两个监听器的 handle 方法中我们打印一个日志来测试一下,如代码 handle 方法所示。

分发和触发事件

我们在某个控制器的方法中来分发事件,也就是触发事件,看监听器是否正常工作。

就是一句话:

event(new UserLogin());
Copy after login

然后我们请求这个控制器,观察日志,发现打印了日志:

[2018-06-17 10:04:29] local.INFO: do something1
[2018-06-17 10:04:29] local.INFO: do something2

那么这个事件-监听机制就正常工作了。

队列异步处理

如果某个监听器需要执行的操作比较慢,可以放到消息队列进行异步处理。

比如把上面的 DoSomething1 改成需要放入队列的,只需要 implements ShoulQueue 接口。

class DoSomething1 implements ShouldQueue
Copy after login

也可以指定队列驱动,如下代码。

/**
     * 任务应该发送到的队列的连接的名称
     *
     * @var string|null
     */
    public $connection = &#39;redis&#39;;
 
    /**
     * 任务应该发送到的队列的名称
     *
     * @var string|null
     */
    public $queue = &#39;listeners&#39;;
Copy after login

我们再次执行控制器方法。

日志里没有打印 do something1,只有 do something2,但是在 redis 队列里发现了一个名为 queues:default 的列表。

{"job":"Illuminate\\Events\\CallQueuedHandler@call","data":{"class":"App\\Listener\\DoSomething1","method":"handle","data":"a:1:{i:0;O:20:\"App\\Events\\UserLogin\":1:{s:6:\"socket\";N;}}"},"id":"3D7VDUwueYGtUvsazicWsifwWQxnnLID","attempts":1}
Copy after login

这个时候需要使用 php artisan queue:work 执行队列任务,才是真正执行 DoSomething1 这个监听器的 handle 方法。

以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!

相关推荐:

Laravel服务提供器(ServiceProvider)的解读

Laravel事件系统的解读

The above is the detailed content of Summary of Laravel event system usage. For more information, please follow other related articles on the PHP Chinese website!

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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Hot Topics

Java Tutorial
1665
14
PHP Tutorial
1270
29
C# Tutorial
1249
24
The Continued Use of PHP: Reasons for Its Endurance The Continued Use of PHP: Reasons for Its Endurance Apr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

The Compatibility of IIS and PHP: A Deep Dive The Compatibility of IIS and PHP: A Deep Dive Apr 22, 2025 am 12:01 AM

IIS and PHP are compatible and are implemented through FastCGI. 1.IIS forwards the .php file request to the FastCGI module through the configuration file. 2. The FastCGI module starts the PHP process to process requests to improve performance and stability. 3. In actual applications, you need to pay attention to configuration details, error debugging and performance optimization.

Laravel vs. Python (with Frameworks): A Comparative Analysis Laravel vs. Python (with Frameworks): A Comparative Analysis Apr 21, 2025 am 12:15 AM

Laravel is suitable for projects that teams are familiar with PHP and require rich features, while Python frameworks depend on project requirements. 1.Laravel provides elegant syntax and rich features, suitable for projects that require rapid development and flexibility. 2. Django is suitable for complex applications because of its "battery inclusion" concept. 3.Flask is suitable for fast prototypes and small projects, providing great flexibility.

What happens if session_start() is called multiple times? What happens if session_start() is called multiple times? Apr 25, 2025 am 12:06 AM

Multiple calls to session_start() will result in warning messages and possible data overwrites. 1) PHP will issue a warning, prompting that the session has been started. 2) It may cause unexpected overwriting of session data. 3) Use session_status() to check the session status to avoid repeated calls.

Using Laravel: Streamlining Web Development with PHP Using Laravel: Streamlining Web Development with PHP Apr 19, 2025 am 12:18 AM

Laravel optimizes the web development process including: 1. Use the routing system to manage the URL structure; 2. Use the Blade template engine to simplify view development; 3. Handle time-consuming tasks through queues; 4. Use EloquentORM to simplify database operations; 5. Follow best practices to improve code quality and maintainability.

Composer: Aiding PHP Development Through AI Composer: Aiding PHP Development Through AI Apr 29, 2025 am 12:27 AM

AI can help optimize the use of Composer. Specific methods include: 1. Dependency management optimization: AI analyzes dependencies, recommends the best version combination, and reduces conflicts. 2. Automated code generation: AI generates composer.json files that conform to best practices. 3. Improve code quality: AI detects potential problems, provides optimization suggestions, and improves code quality. These methods are implemented through machine learning and natural language processing technologies to help developers improve efficiency and code quality.

What database versions are compatible with the latest Laravel? What database versions are compatible with the latest Laravel? Apr 25, 2025 am 12:25 AM

The latest version of Laravel10 is compatible with MySQL 5.7 and above, PostgreSQL 9.6 and above, SQLite 3.8.8 and above, SQLServer 2017 and above. These versions are chosen because they support Laravel's ORM features, such as the JSON data type of MySQL5.7, which improves query and storage efficiency.

What is the difference between php framework laravel and yii What is the difference between php framework laravel and yii Apr 30, 2025 pm 02:24 PM

The main differences between Laravel and Yii are design concepts, functional characteristics and usage scenarios. 1.Laravel focuses on the simplicity and pleasure of development, and provides rich functions such as EloquentORM and Artisan tools, suitable for rapid development and beginners. 2.Yii emphasizes performance and efficiency, is suitable for high-load applications, and provides efficient ActiveRecord and cache systems, but has a steep learning curve.

See all articles