laravel 事件的使用案例


以下是我對事件使用的一些記錄

創建事件

執行以下命令,執行完成后,會在 app\Events 下面出現一個 DeleteEvent.php 文件,事件就在次定義

php artisan make:event DeleteEvent

  

編寫事件
#DeleteEvent.php
<?php

namespace App\Events;

use App\Events\Event;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;

class DeleteEvent extends Event
{
    use SerializesModels;

    public function __construct()
    {
        //
    }

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

  

 
創建監聽listener

執行以下命令,執行完成后,會在 app\Listeners 下面出現一個 DeleteEventListener.php 文件,是對事件 DeleteEvent的監聽

php artisan make:listener --event=DeleteEvent  DeleteEventListener

  

編寫事件監聽
#DeleteEventListener.php
<?php

namespace App\Listeners;

use App\Events\DeleteEvent;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;

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

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

  

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

namespace App\Http\Controllers;

use App\Events\DeleteEvent;
use App\Events\SomeEvent;
use Illuminate\Http\Request;

use App\Http\Requests;

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']);

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM