Laravel Laravel
  • Prologue

    • Release Notes
    • Upgrade Guide
    • Contribution Guide
  • Setup

    • Installation
    • Configuration
    • Homestead
  • The Basics

    • Routing
    • Middleware
    • Controllers
    • Requests
    • Responses
    • Views
  • Architecture Foundations

    • Service Providers
    • Service Container
    • Contracts
    • Facades
    • Request Lifecycle
    • Application Structure
  • Services

    • Authentication
    • Billing
    • Cache
    • Collections
    • Command Bus
    • Core Extension
    • Elixir
    • Encryption
    • Envoy
    • Errors & Logging
    • Events
    • Filesystem / Cloud Storage
    • Hashing
    • Helpers
    • Localization
    • Mail
    • Package Development
    • Pagination
    • Queues
    • Session
    • Templates
    • Unit Testing
    • Validation
  • Database

    • Basic Usage
    • Query Builder
    • Eloquent ORM
    • Schema Builder
    • Migrations & Seeding
    • Redis
  • Artisan CLI

    • Overview
    • Development
Icon

WARNING You're browsing the documentation for an old version of Laravel. Consider upgrading your project to Laravel 11.x.

Events

  • Basic Usage
  • Queued Event Handlers
  • Event Subscribers

Basic Usage

The Laravel event facilities provides a simple observer implementation, allowing you to subscribe and listen for events in your application. Event classes are typically stored in the app/Events directory, while their handlers are stored in app/Handlers/Events.

You can generate a new event class using the Artisan CLI tool:

php artisan make:event PodcastWasPurchased

Subscribing To An Event

The EventServiceProvider included with your Laravel application provides a convenient place to register all event handlers. The listen property contains an array of all events (keys) and their handlers (values). Of course, you may add as many events to this array as your application requires. For example, let's add our PodcastWasPurchased event:

/**
 * The event handler mappings for the application.
 *
 * @var array
 */
protected $listen = [
    'App\Events\PodcastWasPurchased' => [
        'App\Handlers\Events\EmailPurchaseConfirmation',
    ],
];

To generate a handler for an event, use the handler:event Artisan CLI command:

php artisan handler:event EmailPurchaseConfirmation --event=PodcastWasPurchased

Of course, manually running the make:event and handler:event commands each time you need a handler or event is cumbersome. Instead, simply add handlers and events to your EventServiceProvider and use the event:generate command. This command will generate any events or handlers that are listed in your EventServiceProvider:

php artisan event:generate

Firing An Event

Now we are ready to fire our event using the Event facade:

$response = Event::fire(new PodcastWasPurchased($podcast));

The fire method returns an array of responses that you can use to control what happens next in your application.

You may also use the event helper to fire an event:

event(new PodcastWasPurchased($podcast));

Closure Listeners

You can even listen to events without creating a separate handler class at all. For example, in the boot method of your EventServiceProvider, you could do the following:

Event::listen('App\Events\PodcastWasPurchased', function($event)
{
    // Handle the event...
});

Stopping The Propagation Of An Event

Sometimes, you may wish to stop the propagation of an event to other listeners. You may do so using by returning false from your handler:

Event::listen('App\Events\PodcastWasPurchased', function($event)
{
    // Handle the event...

    return false;
});

Queued Event Handlers

Need to queue an event handler? It couldn't be any easier. When generating the handler, simply use the --queued flag:

php artisan handler:event SendPurchaseConfirmation --event=PodcastWasPurchased --queued

This will generate a handler class that implements the Illuminate\Contracts\Queue\ShouldBeQueued interface. That's it! Now when this handler is called for an event, it will be queued automatically by the event dispatcher.

If no exceptions are thrown when the handler is executed by the queue, the queued job will be deleted automatically after it has processed. If you need to access the queued job's delete and release methods manually, you may do so. The Illuminate\Queue\InteractsWithQueue trait, which is included by default on queued handlers, gives you access to these methods:

public function handle(PodcastWasPurchased $event)
{
    if (true)
    {
        $this->release(30);
    }
}

If you have an existing handler that you would like to convert to a queued handler, simply add the ShouldBeQueued interface to the class manually.

Event Subscribers

Defining An Event Subscriber

Event subscribers are classes that may subscribe to multiple events from within the class itself. Subscribers should define a subscribe method, which will be passed an event dispatcher instance:

class UserEventHandler {

    /**
     * Handle user login events.
     */
    public function onUserLogin($event)
    {
        //
    }

    /**
     * Handle user logout events.
     */
    public function onUserLogout($event)
    {
        //
    }

    /**
     * Register the listeners for the subscriber.
     *
     * @param  Illuminate\Events\Dispatcher  $events
     * @return void
     */
    public function subscribe($events)
    {
        $events->listen('App\Events\UserLoggedIn', 'UserEventHandler@onUserLogin');

        $events->listen('App\Events\UserLoggedOut', 'UserEventHandler@onUserLogout');
    }

}

Registering An Event Subscriber

Once the subscriber has been defined, it may be registered with the Event class.

$subscriber = new UserEventHandler;

Event::subscribe($subscriber);

You may also use the service container to resolve your subscriber. To do so, simply pass the name of your subscriber to the subscribe method:

Event::subscribe('UserEventHandler');
last update:2017-05-16 00:44

成为Laravel合作伙伴

Laravel Partners是提供一流Laravel开发和咨询服务的精英商店。我们每个合作伙伴都可以帮助您制定一个精美,结构完善的项目.

我们的伙伴
Laravel
亮点
  • Our Team
  • 发布说明
  • 入门
  • 路由
  • Blade 模板
  • 身份验证
  • 用户授权
  • Artisan 控制台
  • 数据库
  • Eloquent ORM
  • 测试
资源
  • Laravel Bootcamp
  • Laracasts
  • Laravel News
  • Laracon
  • Laracon EU
  • Laracon India
  • Jobs
  • Forums
  • Trademark
  • 版本发布时间
  • 包开发
  • 命令行应用
  • TALL stack全栈开发
  • Blade UI Kit
  • 前端资源构建
伙伴
  • WebReinvent
  • Vehikl
  • Tighten
  • 64 Robots
  • Active Logic
  • Byte 5
  • Curotec
  • Cyber-Duck
  • DevSquad
  • Jump24
  • Kirschbaum
生态系统
  • Cashier
  • Dusk
  • Echo
  • Envoyer
  • Forge
  • Horizon
  • Nova
  • Octane
  • Sail
  • Sanctum
  • Scout
  • Spark
  • Telescope
  • Valet
  • Vapor

Laravel是一个具有表达力,优雅语法的Web应用程序框架。我们认为,发展必须是一种令人愉悦的创造力,才能真正实现。Laravel试图通过减轻大多数Web项目中使用的常见任务来减轻开发的痛苦.

Laravel是Taylor Otwell的商标.
Copyright © 2011-2025 Laravel中文网 LLC.

  • Twitter
  • GitHub
  • Discord
Laravel 全栈开发网 推荐使用阿里云 按Ctrl+D试试