亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

目錄
What Are Events and Listeners?
Step 1: Generate an Event and Listener
Create the Event
Create the Listener
Step 2: Define the Event Class
Step 3: Write the Listener Logic
Step 4: Register the Event and Listeners
Step 5: Dispatch the Event
Optional: Event Discovery
Best Practices
Summary
首頁(yè) php框架 Laravel Laravel活動(dòng)和聽(tīng)眾教程

Laravel活動(dòng)和聽(tīng)眾教程

Jul 29, 2025 am 01:10 AM
php laravel

創(chuàng)建事件和監(jiān)聽(tīng)器:使用Artisan命令生成UserRegistered事件及SendWelcomeEmail、LogUserRegistration監(jiān)聽(tīng)器;2. 定義事件類:在UserRegistered構(gòu)造函數(shù)中註入用戶實(shí)例以便監(jiān)聽(tīng)器訪問(wèn);3. 編寫監(jiān)聽(tīng)器邏輯:SendWelcomeEmail發(fā)送歡迎郵件,LogUserRegistration記錄用戶註冊(cè)日誌;4. 註冊(cè)事件與監(jiān)聽(tīng)器:在EventServiceProvider的$listen數(shù)組中綁定事件與監(jiān)聽(tīng)器;5. 分發(fā)事件:在用戶註冊(cè)後通過(guò)event()或Event::dispatch()觸發(fā)UserRegistered事件,使監(jiān)聽(tīng)器自動(dòng)執(zhí)行;6. 可選啟用事件自動(dòng)發(fā)現(xiàn):設(shè)置shouldDiscoverEvents返回true並運(yùn)行event:cache命令以自動(dòng)註冊(cè)監(jiān)聽(tīng)器;7. 最佳實(shí)踐:保持監(jiān)聽(tīng)器單一職責(zé),耗時(shí)任務(wù)使用ShouldQueue接口實(shí)現(xiàn)隊(duì)列處理,避免在事件中編寫複雜邏輯。該模式通過(guò)解耦業(yè)務(wù)邏輯提升應(yīng)用可維護(hù)性和擴(kuò)展性,適用於通知、日誌、分析等場(chǎng)景。

Laravel events and listeners tutorial

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.

Laravel events and listeners tutorial

What Are Events and Listeners?

  • Event : Something that happened in your app (eg, a user registered).
  • Listener : A class that reacts to that event (eg, 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.

Laravel events and listeners tutorial

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

Laravel events and listeners tutorial

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(&#39;channel-name&#39;);
    }
}

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(&#39;New user registered: &#39; . $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 = [
    &#39;App\Events\UserRegistered&#39; => [
        &#39;App\Listeners\SendWelcomeEmail&#39;,
        &#39;App\Listeners\LogUserRegistration&#39;,
    ],
];

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(&#39;/dashboard&#39;);
}

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)和聽(tīng)眾教程的詳細(xì)內(nèi)容。更多資訊請(qǐng)關(guān)注PHP中文網(wǎng)其他相關(guān)文章!

本網(wǎng)站聲明
本文內(nèi)容由網(wǎng)友自願(yuàn)投稿,版權(quán)歸原作者所有。本站不承擔(dān)相應(yīng)的法律責(zé)任。如發(fā)現(xiàn)涉嫌抄襲或侵權(quán)的內(nèi)容,請(qǐng)聯(lián)絡(luò)admin@php.cn

熱AI工具

Undress AI Tool

Undress AI Tool

免費(fèi)脫衣圖片

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅(qū)動(dòng)的應(yīng)用程序,用於創(chuàng)建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費(fèi)的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費(fèi)的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強(qiáng)大的PHP整合開(kāi)發(fā)環(huán)境

Dreamweaver CS6

Dreamweaver CS6

視覺(jué)化網(wǎng)頁(yè)開(kāi)發(fā)工具

SublimeText3 Mac版

SublimeText3 Mac版

神級(jí)程式碼編輯軟體(SublimeText3)

超越燈堆:PHP在現(xiàn)代企業(yè)體系結(jié)構(gòu)中的作用 超越燈堆:PHP在現(xiàn)代企業(yè)體系結(jié)構(gòu)中的作用 Jul 27, 2025 am 04:31 AM

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

用PHP和RabbitMQ建造彈性微服務(wù) 用PHP和RabbitMQ建造彈性微服務(wù) Jul 27, 2025 am 04:32 AM

要構(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ì)列安全處理失??;4.通過(guò)supervisord等工具守護(hù)消費(fèi)者進(jìn)程並啟用心跳機(jī)制保障服務(wù)健康;最終實(shí)現(xiàn)系統(tǒng)在故障中持續(xù)運(yùn)作的能力。

為PHP創(chuàng)建準(zhǔn)備生產(chǎn)的Docker環(huán)境 為PHP創(chuàng)建準(zhǔn)備生產(chǎn)的Docker環(huán)境 Jul 27, 2025 am 04:32 AM

使用正確的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.採(cǎi)用多階段構(gòu)建優(yōu)化鏡像,移除開(kāi)發(fā)依賴,設(shè)置非root用戶運(yùn)行容器;5.可選Supervisord管理多個(gè)進(jìn)程如cron;6.部署前驗(yàn)證無(wú)敏感信息洩

PHP中的對(duì)象關(guān)聯(lián)映射(ORM)性能調(diào)整 PHP中的對(duì)象關(guān)聯(lián)映射(ORM)性能調(diào)整 Jul 29, 2025 am 05:00 AM

避免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)化,在保持開(kāi)發(fā)效率的同時(shí)確保應(yīng)用性能。

無(wú)服務(wù)器革命:使用BREF部署可擴(kuò)展的PHP應(yīng)用程序 無(wú)服務(wù)器革命:使用BREF部署可擴(kuò)展的PHP應(yīng)用程序 Jul 28, 2025 am 04:39 AM

Bref使PHP開(kāi)發(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提供解決

在PHP中構(gòu)建不變的物體,並具有可讀的屬性 在PHP中構(gòu)建不變的物體,並具有可讀的屬性 Jul 30, 2025 am 05:40 AM

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

將PHP與機(jī)器學(xué)習(xí)模型集成 將PHP與機(jī)器學(xué)習(xí)模型集成 Jul 28, 2025 am 04:37 AM

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

python檢查字典中是否存在關(guān)鍵 python檢查字典中是否存在關(guān)鍵 Jul 27, 2025 am 03:08 AM

推薦使用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)景。

See all articles