laravel event事件 讲解

来源:互联网 发布:java redis list 存取 编辑:程序博客网 时间:2024/05/06 20:51
event注册简单event首先在 EventServiceProvider中的属性$listen添加事件和监听  protected $listen = [        'App\Events\openEvent' => [//事件            'App\Listeners\openListener',//监听器        ],    ];    执行php artisan event:generate    会生成 events/App\Events\openEvent.php Listeners/App\Listeners\openListener    events/App\Events\openEvent.php    中添加    public function __construct($show)    {        $this->show = $show;    }    则此时的 events属性show 就是 事件标识Listeners/App\Listeners\openListener 下的    public function handle(openEvent $event)    {           }    event 就是事件对象,$event->show 就是我们的事件标识    在控制器方法中使用    use App\Events\showEvent;   use Event;    Event::fire(new showEvent('事件标识'));或者全局函数    event(new showEvent('事件标识'));    此时监听器就会自动执行并根据事件的标识执行不同的操作    2. 手动定义事件providers/EventServiceProvider.php    public function boot(DispatcherContract $events)    {        parent::boot($events);        $events->listen('event.show', function($listen){            dd($listen);    });ps event.show 是我们定义的事件标识 闭包参数使我们传递的事件数据党控制器调用Event::fire('event.show',['show1']);时  则会执行providers/EventServiceProvider.php 相对应的事件 并把第二个参数传到 闭包函数    在控制器中执行 Event::fire('event.show',['show1']);    3. 为防止事件堵塞程序 ,使用队列列化的事件 只需要使监听器实现ShouldQueue 接口    namespace App\Listeners;   use App\Events\showEvent;   use Illuminate\Queue\InteractsWithQueue;   use Illuminate\Contracts\Queue\ShouldQueue;   class showListener implements ShouldQueue    4.事件的合集 事件订阅器EventServiceProvider中添加    protected $subscribe = [        'App\Listeners\subscribetListener',//注册事件订阅器    ];    事件订阅器实现namespace App\Listeners;class subscrListener{    /**     * 处理用户登录事件。     */    public function onUserLogin($event) {    }    /**     * 处理用户注销事件。     */    public function onUserLogout($event) {    }    /**     * 注册侦听器的订阅者。     *     * @param  Illuminate\Events\Dispatcher  $events     */    public function subscribe($events)    {        $events->listen(            'App\Events\UserLoggedIn',            'App\Listeners\subscrListener@onUserLogin'//UserLoggedIn 事件的监听者是 onUserLogin 方法        );        $events->listen(            'App\Events\UserLoggedOut',            'App\Listeners\subscrListener@onUserLogout'//UserLoggedOut 事件的监听者是 onUserLogout 方法        );    }}控制器调用        Event::fire(new UserLoggedIn('UserLoggedIn'));               Event::fire(new UserLoggedOut('UserLoggedOut'));
原创粉丝点击