Laravel 配置 SqlDebug 服务,进行实时监听打印 SQL

0:释义

什么是服务容器
简而言之,Laravel 服务容器 是一个用于存储绑定组件的盒子,它还会为应用提供所需的服务。
Laravel 服务容器是用于管理类的依赖和执行依赖注入的工具,By Laravel 文档。

什么是服务提供者
如果说服务容器是提供绑定和依赖注入的的工具,那么 服务提供者 则是实现绑定的工具。

1:自定义服务提供者

php artisan make:provider SqlDebugServiceProvider

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

namespace AppProviders;

use IlluminateSupportServiceProvider;

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...
         */
        AppProvidersAppServiceProvider::class,
        AppProvidersAuthServiceProvider::class,
        // AppProvidersBroadcastServiceProvider::class,
        AppProvidersEventServiceProvider::class,
        AppProvidersRouteServiceProvider::class,
        /**
         * SQL 监听服务
         */
        AppProvidersSqlDebugServiceProvider::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 文件

原文地址:https://www.cnblogs.com/laowenBlog/p/13397218.html