Laravel framework realizes sql statement recording function by using listener

  • 2021-10-15 10:03:03
  • OfStack

This paper describes the Laravel framework using listeners to record sql statements. Share it for your reference, as follows:

Recording sql statements with listeners

1. The event class for listening to sql statement has been defined. Just create a listener class directly:


#  Eavesdropping 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);
    #  Here $uid Definition is dependent on middleware to record operation log code 
    $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. Introduce a 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 carried out at this time

Related articles:

Laravel Framework Realizes Operation Log Recording Using Middleware

For more readers interested in Laravel related content, please check the topics on this site: "Introduction and Advanced Tutorial of Laravel Framework", "Summary of Excellent Development Framework of php", "Introduction Tutorial of php Object-Oriented Programming", "Introduction Tutorial of php+mysql Database Operation" and "Summary of Common Database Operation Skills of php"

I hope this article is helpful to the PHP programming based on Laravel framework.


Related articles: