Laravel 配置 SqlDebug 服務,進行實時監聽打印 SQL

0:釋義

什麼是服務容器
簡而言之,Laravel 服務容器 是一個用於存儲綁定組件的盒子,它還會爲應用提供所需的服務。
Laravel 服務容器是用於管理類的依賴和執行依賴注入的工具,By Laravel 文檔。

什麼是服務提供者
若是說服務容器是提供綁定和依賴注入的的工具,那麼 服務提供者 則是實現綁定的工具。

1:自定義服務提供者

php artisan make:provider SqlDebugServiceProvider

# Explanation:
# SqlDebugServiceProvider 自定義服務提供者的名字
<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class SqlDebugServiceProvider extends ServiceProvider
{
    /**
     * Register services.
     * register 方法用於執行服務綁定處理
     * 
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * Bootstrap services.
     * 可使用全部已綁定的服務
     *
     * @return void
     */
    public function boot()
    {
        //
    }
}

2:註冊自定義服務提供者

爲了完成註冊服務提供者的功能,僅須要將類名加入到 config/app.php 配置文件的 providers 節點。
'providers' => [

        /*
         * Application Service Providers...
         */
        App\Providers\AppServiceProvider::class,
        App\Providers\AuthServiceProvider::class,
        // App\Providers\BroadcastServiceProvider::class,
        App\Providers\EventServiceProvider::class,
        App\Providers\RouteServiceProvider::class,
        /**
         * SQL 監聽服務
         */
        App\Providers\SqlDebugServiceProvider::class,

    ],

3: 在 中 boot 方法中增長 SQL 監聽服務

\DB::listen(function ($query) {
    $tmp = str_replace('?', '"' . '%s' . '"', $query->sql);
    $qBindings = [];
    foreach ($query->bindings as $key => $value) {
        if (is_numeric($key)) {
            $qBindings[] = $value;
        } else {
            $tmp = str_replace(':' . $key, '"' . $value . '"', $tmp);
        }
    }
    $tmp = vsprintf($tmp, $qBindings);
    $tmp = str_replace("\\", "", $tmp);
    \Log::debug('[execution time: ' . $query->time . 'ms] ' . $tmp);
});

4: 會發如今 /storage/logs/ 目錄下生成對應的 SQL 文件

相關文章
相關標籤/搜索