Laravel中编写事件和事件监听器
分类:PHP
阅读 (1,699)
7月 112019
一、简单介绍事件和监听器
事件Event:主要用做数据的载体,里面只是包含要传递的数据。
监听器Listener:事件真正被触发的地方,其handle方法接受传入的Event对象,并在此处理Event中带来的数据。
二、首先定义事件和事件监听器
打开App\Providers\EventServiceProvider.php,给$listen数组赋值要添加的事件和监听器,可定义多个事件,每个事件也可以定义多个监听器。
比如:
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 36 |
<?php namespace App\Providers; use Illuminate\Contracts\Events\Dispatcher as DispatcherContract; use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider; class EventServiceProvider extends ServiceProvider { /** * The event listener mappings for the application. * * @var array */ protected $listen = [ 'App\Events\UserReigisterEvent' => [ 'App\Listeners\UserRegisterListener', ], 'App\Events\UserLoginEvent' => [ 'App\Listeners\UserLoginListener', ], ]; /** * Register any other events for your application. * * @param \Illuminate\Contracts\Events\Dispatcher $events * @return void */ public function boot(DispatcherContract $events) { parent::boot($events); // } } |
三、在控制台生成相关文件
在控制台输入命令:
php artisan event:generate
执行完以后可以看到App\Event和App\Listeners两个目录下多了相应的php类
四、定义Event类
Event类主要用于运输数据,在_construct函数的参数中传入,并将值保存在内部成员变量中,示例如下:
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 36 37 38 |
<?php namespace App\Events; use App\Events\Event; use Illuminate\Queue\SerializesModels; use Illuminate\Contracts\Broadcasting\ShouldBroadcast; use App\User; class UserLoginEvent extends Event { use SerializesModels; public $user; public $logintimes; /** * Create a new event instance. * * @return void */ public function __construct(User $_user, $_logintimes) { $this->user = $_user; $this->logintimes = $_logintimes; } /** * Get the channels the event should be broadcast on. * * @return array */ public function broadcastOn() { return []; } } |
五、Listener中处理事件
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 |
<?php namespace App\Listeners; use App\Events\UserLoginEvent; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Contracts\Queue\ShouldQueue; class UserLoginListener { /** * Create the event listener. * * @return void */ public function __construct() { // } /** * Handle the event. * * @param UserLoginEvent $event * @return void */ public function handle(UserLoginEvent $event) { echo $event->logintimes; echo $event->user->username; } } |
六、触发事件
比如在用户登录成功的地方调用前面定义的事件
1 2 |
$loginevent = new UserLoginEvent($loginuser, $logintimes); event($loginevent); |
Sorry, the comment form is closed at this time.