創(chuàng)建事件和監(jiān)聽器:使用Artisan命令生成UserRegistered事件及SendWelcomeEmail、LogUserRegistration監(jiān)聽器;2. 定義事件類:在UserRegistered構(gòu)造函數(shù)中注入用戶實(shí)例以便監(jiān)聽器訪問(wèn);3. 編寫監(jiān)聽器邏輯:SendWelcomeEmail發(fā)送歡迎郵件,LogUserRegistration記錄用戶注冊(cè)日志;4. 注冊(cè)事件與監(jiān)聽器:在EventServiceProvider的$listen數(shù)組中綁定事件與監(jiān)聽器;5. 分發(fā)事件:在用戶注冊(cè)后通過(guò)event()或Event::dispatch()觸發(fā)UserRegistered事件,使監(jiān)聽器自動(dòng)執(zhí)行;6. 可選啟用事件自動(dòng)發(fā)現(xiàn):設(shè)置shouldDiscoverEvents返回true并運(yùn)行event:cache命令以自動(dòng)注冊(cè)監(jiān)聽器;7. 最佳實(shí)踐:保持監(jiān)聽器單一職責(zé),耗時(shí)任務(wù)使用ShouldQueue接口實(shí)現(xiàn)隊(duì)列處理,避免在事件中編寫復(fù)雜邏輯。該模式通過(guò)解耦業(yè)務(wù)邏輯提升應(yīng)用可維護(hù)性和擴(kuò)展性,適用于通知、日志、分析等場(chǎng)景。
Laravel Events and Listeners are a powerful way to make your application more modular and maintainable by decoupling actions from the code that triggers them. Instead of writing long, tightly coupled logic in your controllers or models, you can dispatch events and let listeners react to them. This tutorial walks you through setting up and using events and listeners in Laravel with a practical example.

What Are Events and Listeners?
- Event: Something that happened in your app (e.g., a user registered).
- Listener: A class that reacts to that event (e.g., send a welcome email, log activity).
This pattern follows the observer pattern, allowing one part of your app to notify others without knowing who’s listening.
Step 1: Generate an Event and Listener
Laravel makes it easy to create events and listeners using Artisan commands.

Let’s say we want to send a welcome email and log user registration.
Create the Event
php artisan make:event UserRegistered
This creates a file: app/Events/UserRegistered.php

Create the Listener
php artisan make:listener SendWelcomeEmail --event=UserRegistered php artisan make:listener LogUserRegistration --event=UserRegistered
This creates:
app/Listeners/SendWelcomeEmail.php
app/Listeners/LogUserRegistration.php
You can also create listeners without specifying the event and wire them manually later.
Step 2: Define the Event Class
Open app/Events/UserRegistered.php
. It should look like this:
<?php namespace App\Events; use App\Models\User; use Illuminate\Broadcasting\Channel; use Illuminate\Broadcasting\InteractsWithSockets; use Illuminate\Broadcasting\PresenceChannel; use Illuminate\Broadcasting\PrivateChannel; use Illuminate\Contracts\Broadcasting\ShouldBroadcast; use Illuminate\Foundation\Events\Dispatchable; use Illuminate\Queue\SerializesModels; class UserRegistered { use Dispatchable, InteractsWithSockets, SerializesModels; public $user; public function __construct(User $user) { $this->user = $user; } public function broadcastOn() { return new PrivateChannel('channel-name'); } }
We’re passing the $user
model to the event so listeners can access it.
Step 3: Write the Listener Logic
Open app/Listeners/SendWelcomeEmail.php
:
<?php namespace App\Listeners; use App\Events\UserRegistered; use Illuminate\Support\Facades\Mail; use App\Mail\WelcomeEmail; class SendWelcomeEmail { public function handle(UserRegistered $event) { Mail::to($event->user->email)->send(new WelcomeEmail($event->user)); } }
Make sure you have a WelcomeEmail
Mailable:
php artisan make:mail WelcomeEmail
Similarly, for logging:
<?php namespace App\Listeners; use App\Events\UserRegistered; use Illuminate\Support\Facades\Log; class LogUserRegistration { public function handle(UserRegistered $event) { Log::info('New user registered: ' . $event->user->email); } }
Step 4: Register the Event and Listeners
Open app/Providers/EventServiceProvider.php
.
In the $listen
array, map the event to its listeners:
protected $listen = [ 'App\Events\UserRegistered' => [ 'App\Listeners\SendWelcomeEmail', 'App\Listeners\LogUserRegistration', ], ];
This tells Laravel which listeners should run when UserRegistered
is dispatched.
After making changes here, run:
php artisan event:cache
(for production; not required in local during development)
Step 5: Dispatch the Event
Now, trigger the event from your controller or model.
In your RegisterController
or wherever user registration happens:
use App\Events\UserRegistered; use Illuminate\Support\Facades\Event; // After user creation event(new UserRegistered($user)); // Or using the Event facade Event::dispatch(new UserRegistered($user));
Example in a controller method:
public function register(Request $request) { $user = User::create($request->validated()); event(new UserRegistered($user)); return redirect('/dashboard'); }
When this runs, both listeners will execute.
Optional: Event Discovery
If you don’t want to manually register events in EventServiceProvider
, Laravel can auto-discover them.
Enable it in EventServiceProvider
:
public function shouldDiscoverEvents() { return true; }
Laravel will scan the Listeners
directory and auto-register event-listener pairs based on type-hinting in the handle()
method.
Then you don’t need to list them in $listen
.
Run:
php artisan event:cache
Best Practices
- Keep listeners focused: One job per listener.
- Use queueable listeners for slow tasks (like sending emails):
class SendWelcomeEmail implements ShouldQueue { use Queueable; }
Make sure your listener uses the Queueable
trait and implements ShouldQueue
.
- Avoid heavy logic in events; use them just to signal.
Summary
Events and listeners help you write cleaner, more scalable Laravel apps by separating concerns. You’ve now:
- Created an event (
UserRegistered
) - Made listeners (
SendWelcomeEmail
,LogUserRegistration
) - Registered them in
EventServiceProvider
- Dispatched the event from your code
This pattern is great for audit logging, notifications, analytics, and more.
Basically, if something happens and other parts of your app need to know — use events.
以上是Laravel活動(dòng)和聽眾教程的詳細(xì)內(nèi)容。更多信息請(qǐng)關(guān)注PHP中文網(wǎng)其他相關(guān)文章!

熱AI工具

Undress AI Tool
免費(fèi)脫衣服圖片

Undresser.AI Undress
人工智能驅(qū)動(dòng)的應(yīng)用程序,用于創(chuàng)建逼真的裸體照片

AI Clothes Remover
用于從照片中去除衣服的在線人工智能工具。

Clothoff.io
AI脫衣機(jī)

Video Face Swap
使用我們完全免費(fèi)的人工智能換臉工具輕松在任何視頻中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費(fèi)的代碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
功能強(qiáng)大的PHP集成開發(fā)環(huán)境

Dreamweaver CS6
視覺化網(wǎng)頁(yè)開發(fā)工具

SublimeText3 Mac版
神級(jí)代碼編輯軟件(SublimeText3)

PHPisstillrelevantinmodernenterpriseenvironments.1.ModernPHP(7.xand8.x)offersperformancegains,stricttyping,JITcompilation,andmodernsyntax,makingitsuitableforlarge-scaleapplications.2.PHPintegrateseffectivelyinhybridarchitectures,servingasanAPIgateway

要構(gòu)建彈性的PHP微服務(wù),需使用RabbitMQ實(shí)現(xiàn)異步通信,1.通過(guò)消息隊(duì)列解耦服務(wù),避免級(jí)聯(lián)故障;2.配置持久化隊(duì)列、持久化消息、發(fā)布確認(rèn)和手動(dòng)ACK以確??煽啃裕?.使用指數(shù)退避重試、TTL和死信隊(duì)列安全處理失?。?.通過(guò)supervisord等工具守護(hù)消費(fèi)者進(jìn)程并啟用心跳機(jī)制保障服務(wù)健康;最終實(shí)現(xiàn)系統(tǒng)在故障中持續(xù)運(yùn)作的能力。

使用正確的PHP基礎(chǔ)鏡像并配置安全、性能優(yōu)化的Docker環(huán)境是實(shí)現(xiàn)生產(chǎn)就緒的關(guān)鍵。1.選用php:8.3-fpm-alpine作為基礎(chǔ)鏡像以減少攻擊面并提升性能;2.通過(guò)自定義php.ini禁用危險(xiǎn)函數(shù)、關(guān)閉錯(cuò)誤顯示并啟用Opcache及JIT以增強(qiáng)安全與性能;3.使用Nginx作為反向代理,限制訪問(wèn)敏感文件并正確轉(zhuǎn)發(fā)PHP請(qǐng)求至PHP-FPM;4.采用多階段構(gòu)建優(yōu)化鏡像,移除開發(fā)依賴,設(shè)置非root用戶運(yùn)行容器;5.可選Supervisord管理多個(gè)進(jìn)程如cron;6.部署前驗(yàn)證無(wú)敏感信息泄

避免N 1查詢問(wèn)題,通過(guò)提前加載關(guān)聯(lián)數(shù)據(jù)來(lái)減少數(shù)據(jù)庫(kù)查詢次數(shù);2.僅選擇所需字段,避免加載完整實(shí)體以節(jié)省內(nèi)存和帶寬;3.合理使用緩存策略,如Doctrine的二級(jí)緩存或Redis緩存高頻查詢結(jié)果;4.優(yōu)化實(shí)體生命周期,定期調(diào)用clear()釋放內(nèi)存以防止內(nèi)存溢出;5.確保數(shù)據(jù)庫(kù)索引存在并分析生成的SQL語(yǔ)句以避免低效查詢;6.在無(wú)需跟蹤變更的場(chǎng)景下禁用自動(dòng)變更跟蹤,改用數(shù)組或輕量模式提升性能。正確使用ORM需結(jié)合SQL監(jiān)控、緩存、批量處理和適當(dāng)優(yōu)化,在保持開發(fā)效率的同時(shí)確保應(yīng)用性能。

ReadonlypropertiesinPHP8.2canonlybeassignedonceintheconstructororatdeclarationandcannotbemodifiedafterward,enforcingimmutabilityatthelanguagelevel.2.Toachievedeepimmutability,wrapmutabletypeslikearraysinArrayObjectorusecustomimmutablecollectionssucha

Bref使PHP開發(fā)者能無(wú)需管理服務(wù)器即可構(gòu)建可擴(kuò)展、成本高效的應(yīng)用。1.Bref通過(guò)提供優(yōu)化的PHP運(yùn)行時(shí)層,將PHP帶入AWSLambda,支持PHP8.3等版本,并與Laravel、Symfony等框架無(wú)縫集成;2.部署步驟包括:使用Composer安裝Bref,配置serverless.yml定義函數(shù)和事件,如HTTP端點(diǎn)和Artisan命令;3.執(zhí)行serverlessdeploy命令即可完成部署,自動(dòng)配置APIGateway并生成訪問(wèn)URL;4.針對(duì)Lambda限制,Bref提供解決

usearestapitobridgephpandmlmodelsbyrunningthemodelinpythonviaflaskorfastapiandcallingitfromphpusingcurlorguzzle.2.runpythonscriptsdirectsdirectlyectlyectlyfromphpsingexec()orshell_exec()orshell_exec()orshell_exec()

推薦使用in關(guān)鍵字檢查字典中是否存在某個(gè)鍵,因?yàn)樗?jiǎn)潔、高效且可讀性強(qiáng);2.不推薦使用get()方法判斷鍵是否存在,因?yàn)楫?dāng)鍵存在但值為None時(shí)會(huì)誤判;3.可以使用keys()方法,但多余,因in默認(rèn)即檢查鍵;4.在需要取值且預(yù)期鍵通常存在時(shí),可用try-except捕獲KeyError異常。最推薦的做法是使用in關(guān)鍵字,既安全又高效,且不受值為None的影響,適合絕大多數(shù)場(chǎng)景。
