Laravel Event和Listener

make:event TestEvent 创建一个新事件类
php artisan make:listener TestListener –event TestEvent 创建一个listener类
注册事件TestEvent
/**
* Create a new event instance.
*
* @return void
*/
public function __construct($str)
{
$this->data = $str;
}

/**
* Get the channels the event should broadcast on.
*
* @return Channel|array
*/
public function broadcastOn()
{
return [];
}
监听时间TestListener
/**
* Create the event listener.
*
* @return void
*/
public function __construct()
{
//
}

/**
* Handle the event.
*
* @param TestEvent $event
* @return void
*/
public function handle(TestEvent $event)
{
file_put_contents(‘/data/tmp/test.log’, $event->data, FILE_APPEND);
}
注册应用关联事件EventServiceProvider.php
protected $listen = [

‘app\Events\TestEvent’ => [
‘app\Listeners\TestListener’,
],
];
触发事件
$str = ‘test….’;
Event::fire(new TestEvent($str));
event(new TestEvent($str));

php artisan event:generate 批量生成event和listen 编辑EventServiceProvider.php

备注:事件可以广播,通过websocket服务,依赖Redis的pub和sub模式



Tagged , , . Bookmark the permalink.

Comments are closed.