1. 程式人生 > >laravel 事件與監聽

laravel 事件與監聽

簡介

  • 針對於 lumen,具體版本如下:
    Laravel Framework Lumen (5.7.3) (Laravel Components 5.7.*)

實際操作(記錄 sql 以及執行時間)

註冊對映關係

  • EventServiceProvider中註冊事件與監聽器之間的對映關係:
        'App\Events\SqlRecorded' => [
            'App\Listeners\RecordSqlNotification',
        ],

開啟事件服務

  • lumen 預設不開啟,在 bootstrap/app.php
    檔案中註冊
 $app->register(App\Providers\EventServiceProvider::class);

建立事件 event

  • 檔案 app/Events/SqlRecorded.php
<?php

namespace App\Events;

use Illuminate\Support\Facades\DB;

class SqlRecorded extends Event
{
    /**
     * Create a new event instance.
     *
     * @return void
     */
public function __construct() { DB::connection()->enableQueryLog(); } public function broadcastOn() { return []; } }

建立監聽 listen

  • 檔案 app/Listeners/RecordSqlNotification.php
<?php

namespace App\Listeners;

use App\Events\SqlRecorded;
use Illuminate\
Queue\InteractsWithQueue
; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Support\Facades\DB; class RecordSqlNotification { /** * Create the event listener. * * @return void */ public function __construct() { // } /** * Handle the event. * * @param SqlRecorded $event * @return void */ public function handle(SqlRecorded $event) { $path = storage_path('logs') . DIRECTORY_SEPARATOR . 'sql-' . date('Y-m-d') . '.log'; $queries = $this->refactor(); file_put_contents($path, json_encode($queries) . "\n", FILE_APPEND); } public function refactor() { $queries = DB::getQueryLog(); foreach ($queries as &$query) { $bindings = count($query['bindings']); if ($bindings > 0) { $search = array_fill(0, $bindings, '?'); $sql = str_replace($search, $query['bindings'], $query['query']); $query['query'] = $sql; } $query = [ 'query' => $query['query'], 'time' => $query['time'] ]; } return $queries; } }

訪問控制器

    public function event()
    {
        $event = new SqlRecorded();
        $res = (new User())->where('username', 'Jerry')->where('gender', 1)->get();
        /*分發事件,此時事件將被監聽,以下兩種方式都可以實現*/
        event($event);
        //event::fire($event);
    }

結束

  • 註冊路由後即可訪問控制方法,並將sql存入指定檔案。