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 檔案
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/3665.html
標籤:PHP
上一篇:Laravel 定時任務調度 的 Artisan 命令調度
下一篇:python 采集唯美girl
