laravel 事件的使用案例

以下是我对事件使用的一些记录

创建事件

执行以下命令,执行完成后,会在 appEvents 下面出现一个 DeleteEvent.php 文件,事件就在次定义

php artisan make:event DeleteEvent

  

编写事件
#DeleteEvent.php
<?php

namespace AppEvents;

use AppEventsEvent;
use IlluminateQueueSerializesModels;
use IlluminateContractsBroadcastingShouldBroadcast;

class DeleteEvent extends Event
{
    use SerializesModels;

    public function __construct()
    {
        //
    }

    public function broadcastOn()
    {
        print 'delete event';
    }
}

  

 
创建监听listener

执行以下命令,执行完成后,会在 appListeners 下面出现一个 DeleteEventListener.php 文件,是对事件 DeleteEvent的监听

php artisan make:listener --event=DeleteEvent  DeleteEventListener

  

编写事件监听
#DeleteEventListener.php
<?php

namespace AppListeners;

use AppEventsDeleteEvent;
use IlluminateQueueInteractsWithQueue;
use IlluminateContractsQueueShouldQueue;

class DeleteEventListener
{
    public function __construct()
    {
        //
    }

    public function handle(DeleteEvent $event)
    {
        //
        $event->broadcastOn();
    }
}

  

 
调用事件-在控制器使用
#EventController.php
<?php

namespace AppHttpControllers;

use AppEventsDeleteEvent;
use AppEventsSomeEvent;
use IlluminateHttpRequest;

use AppHttpRequests;

class EventController extends Controller
{
    //
    public function index()
    {
//        event(new SomeEvent());       //框架默认调用broadcastOn()

        $event = new DeleteEvent();     //自定义 
        event($event->broadcastOn());
    }
}

  

 
编写路由
#routes.php
Route::get('/event',['uses'=>'EventController@index']);

  

 
原文地址:https://www.cnblogs.com/zeopean/p/5999885.html