Home  >  Article  >  Backend Development  >  Laravel framework implements the function of using listeners to record sql statements

Laravel framework implements the function of using listeners to record sql statements

不言
不言Original
2018-06-07 09:48:201698browse

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

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn