This article mainly introduces the Laravel framework to implement the function of using listeners to record sql statements. It analyzes the creation and introduction of the Laravel framework listener and the related operating skills of using the listener to record sql statements in the form of examples. Friends who need it can Refer to the following
The example of this article describes how the Laravel framework implements the function of using listeners to record sql statements. Share it with everyone for your reference, the details are as follows:
Use the listener to record sql statements
1. The event class for monitoring sql statements has been defined, just create the listener class directly :
# 监听sql make:listener QueryListener --event=Illuminate\Database\Events\QueryExecuted
2. Listener class code
./app/Listeners/ QueryListener.php
<?php namespace App\Listeners; use Illuminate\Database\Events\QueryExecuted; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Contracts\Queue\ShouldQueue; use App\Http\Models\OperationLog; class QueryListener { /** * Create the event listener. * * @return void */ public function __construct() { // } /** * Handle the event. * * @param QueryExecuted $event * @return void */ public function handle(QueryExecuted $event) { $sql = str_replace("?", "'%s'", $event->sql); $log = vsprintf($sql, $event->bindings); # 此处$uid定义是依赖于中间件记录操作日志代码 $uid = isset($_SERVER['admin_uid']) ? $_SERVER['admin_uid'] : 0; if('select' != substr($log , 0 , 6)){ if('insert into `operationLog`' != substr($log , 0 , 26)){ $OperationLog = new OperationLog(); $OperationLog->uid = $uid; $OperationLog->sql = $log; $OperationLog->input = ''; $OperationLog->save(); } } } }
3. Introducing the listener
./app/Providers /EventServiceProvider.php
protected $listen = [ ... \Illuminate\Database\Events\QueryExecuted::class => [ 'App\Listeners\QueryListener' ], ... ];
The sql log will be recorded when the operation is performed at this time
Related recommendations:
How to implement fuzzy matching and multi-condition query function in Laravel5
The above is the detailed content of Laravel framework implements the function of using listeners to record sql statements. For more information, please follow other related articles on the PHP Chinese website!