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 事件:

1

php artisan make:event UserLogin

Copy after login

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

<?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 中可以定义事件和监听器,如下:

1

2

3

4

5

6

protected $listen = [

    &#39;App\Events\UserLogin&#39; => [

        &#39;App\Lisenter\DoSomething1&#39;,

        &#39;App\Lisenter\Dosomething2&#39;,

    ],

];

Copy after login

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

1

php artisan make:event generate

Copy after login

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

<?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 方法所示。

分发和触发事件

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

就是一句话:

1

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 接口。

1

class DoSomething1 implements ShouldQueue

Copy after login

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

1

2

3

4

5

6

7

8

9

10

11

12

13

/**

     * 任务应该发送到的队列的连接的名称

     *

     * @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 的列表。

1

{"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
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Clair Obscur: Expedition 33 - How To Get Perfect Chroma Catalysts
2 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
1677
14
PHP Tutorial
1278
29
C# Tutorial
1257
24
What is the significance of the session_start() function? What is the significance of the session_start() function? May 03, 2025 am 12:18 AM

session_start()iscrucialinPHPformanagingusersessions.1)Itinitiatesanewsessionifnoneexists,2)resumesanexistingsession,and3)setsasessioncookieforcontinuityacrossrequests,enablingapplicationslikeuserauthenticationandpersonalizedcontent.

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.

How to use MySQL functions for data processing and calculation How to use MySQL functions for data processing and calculation Apr 29, 2025 pm 04:21 PM

MySQL functions can be used for data processing and calculation. 1. Basic usage includes string processing, date calculation and mathematical operations. 2. Advanced usage involves combining multiple functions to implement complex operations. 3. Performance optimization requires avoiding the use of functions in the WHERE clause and using GROUPBY and temporary tables.

Recommended Laravel's best expansion packs: 2024 essential tools Recommended Laravel's best expansion packs: 2024 essential tools Apr 30, 2025 pm 02:18 PM

The essential Laravel extension packages for 2024 include: 1. LaravelDebugbar, used to monitor and debug code; 2. LaravelTelescope, providing detailed application monitoring; 3. LaravelHorizon, managing Redis queue tasks. These expansion packs can improve development efficiency and application performance.

Composer: The Package Manager for PHP Developers Composer: The Package Manager for PHP Developers May 02, 2025 am 12:23 AM

Composer is a dependency management tool for PHP, and manages project dependencies through composer.json file. 1) parse composer.json to obtain dependency information; 2) parse dependencies to form a dependency tree; 3) download and install dependencies from Packagist to the vendor directory; 4) generate composer.lock file to lock the dependency version to ensure team consistency and project maintainability.

Laravel logs and error monitoring: Sentry and Bugsnag integration Laravel logs and error monitoring: Sentry and Bugsnag integration Apr 30, 2025 pm 02:39 PM

Integrating Sentry and Bugsnag in Laravel can improve application stability and performance. 1. Add SentrySDK in composer.json. 2. Add Sentry service provider in config/app.php. 3. Configure SentryDSN in the .env file. 4. Add Sentry error report in App\Exceptions\Handler.php. 5. Use Sentry to catch and report exceptions and add additional context information. 6. Add Bugsnag error report in App\Exceptions\Handler.php. 7. Use Bugsnag monitoring

Laravel Live Chat Application: WebSocket and Pusher Laravel Live Chat Application: WebSocket and Pusher Apr 30, 2025 pm 02:33 PM

Building a live chat application in Laravel requires using WebSocket and Pusher. The specific steps include: 1) Configure Pusher information in the .env file; 2) Set the broadcasting driver in the broadcasting.php file to Pusher; 3) Subscribe to the Pusher channel and listen to events using LaravelEcho; 4) Send messages through Pusher API; 5) Implement private channel and user authentication; 6) Perform performance optimization and debugging.

Laravel N 1 query problem: How to solve it with Eager Loading? Laravel N 1 query problem: How to solve it with Eager Loading? Apr 30, 2025 pm 01:57 PM

EagerLoading can solve N 1 query problems in Laravel. 1) Use the with method to preload relevant model data, such as User::with('posts')->get(). 2) For nested relationships, use with('posts.comments'). 3) Avoid overuse, selective loading, and use the load method as needed. Through these methods, the number of queries can be significantly reduced and the application performance can be improved.

See all articles