Laravel - 事件处理
事件提供了一个简单的观察者实现,允许用户订阅和监听在 Web 应用程序中触发的各种事件。Laravel 中的所有事件类都存储在 app/Events 文件夹中,而监听器则存储在 app/Listeners 文件夹中。
用于在 Web 应用程序中生成事件和监听器的 artisan 命令如下所示 −
php artisan event:generate
此命令将事件和监听器生成到上述相应的文件夹中。
事件和监听器是解耦 Web 应用程序的好方法,因为一个事件可以有多个彼此独立的监听器。 artisan 命令创建的 events 文件夹包含以下两个文件:event.php 和 SomeEvent.php。它们显示在这里 −
Event.php
<?php namespace App\Events; abstract class Event{ // }
如上所述,event.php 包含类 Event 的基本定义并调用命名空间 App\Events。请注意,用户定义或自定义事件在此文件中创建。
SomeEvent.php
<?php namespace App\Events; use App\Events\Event; use Illuminate\Queue\SerializesModels; use Illuminate\Contracts\Broadcasting\ShouldBroadcast; class SomeEvent extends Event{ use SerializesModels; /** * Create a new event instance. * * @return void */ public function __construct() { // } /** * Get the channels the event should be broadcast on. * * @return array */ public function broadcastOn() { return []; } }
请注意,此文件使用序列化在 Web 应用程序中广播事件,并且必要的参数也在此文件中初始化。
例如,如果我们需要在构造函数中初始化 order 变量以注册事件,我们可以按以下方式执行 −
public function __construct(Order $order) { $this->order = $order; }
侦听器
侦听器处理正在注册的事件中提到的所有活动。artisan 命令 event:generate 在 app/listeners 目录中创建所有 侦听器。Listeners 文件夹包含一个文件 EventListener.php,其中包含处理侦听器所需的所有方法。
EventListener.php
<?php namespace App\Listeners; use App\Events\SomeEvent; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Contracts\Queue\ShouldQueue; class EventListener{ /** * Create the event listener. * * @return void */ public function __construct() { // } /** * Handle the event. * * @param SomeEvent $event * @return void */ public function handle(SomeEvent $event) { // } }
如代码中所述,它包含用于管理各种事件的handle函数。我们可以创建针对单个事件的各种独立侦听器。