需要安装数据库扩展:

    1. composer require vlucas/phpdotenv ^5.1.0
    2. composer require illuminate/database ^8.0
    3. composer require illuminate/events # 监听sql语句需要这个,否则不需要


    support/bootstrap/db/laravel.php 文件中添加sql监听语句

    1. <?php
    2. /**
    3. * This file is part of webman.
    4. *
    5. * Licensed under The MIT License
    6. * For full copyright and license information, please see the MIT-LICENSE.txt
    7. * Redistributions of files must retain the above copyright notice.
    8. *
    9. * @author walkor<walkor@workerman.net>
    10. * @copyright walkor<walkor@workerman.net>
    11. * @link http://www.workerman.net/
    12. * @license http://www.opensource.org/licenses/mit-license.php MIT License
    13. */
    14. namespace support\bootstrap\db;
    15. use support\bootstrap\Log;
    16. use Webman\Bootstrap;
    17. use Illuminate\Database\Capsule\Manager as Capsule;
    18. use Illuminate\Events\Dispatcher;
    19. use Illuminate\Container\Container;
    20. use Workerman\Worker;
    21. /**
    22. * Class Laravel
    23. * @package support\bootstrap\db
    24. */
    25. class Laravel implements Bootstrap
    26. {
    27. /**
    28. * @param Worker $worker
    29. *
    30. * @return void
    31. */
    32. public static function start($worker)
    33. {
    34. if (!class_exists('\Illuminate\Database\Capsule\Manager')) {
    35. return;
    36. }
    37. $capsule = new Capsule;
    38. $configs = config('database');
    39. $default_config = $configs['connections'][$configs['default']];
    40. $capsule->addConnection($default_config);
    41. foreach ($configs['connections'] as $name => $config) {
    42. $capsule->addConnection($config, $name);
    43. }
    44. if (class_exists('\Illuminate\Events\Dispatcher')) {
    45. $capsule->setEventDispatcher(new Dispatcher(new Container));
    46. }
    47. $capsule->setAsGlobal();
    48. # sql语句监听
    49. if(env('APP_DEBUG')){
    50. Capsule::connection()->listen(function ($query) {
    51. //这里是执行sql后的监听回调方法
    52. $sql = vsprintf(str_replace("?", "'%s'", $query->sql), $query->bindings) . " \t[" . $query->time . ' ms] ';
    53. // 把SQL写入到日志文件中
    54. echo $sql . PHP_EOL;
    55. Log::debug($sql);
    56. });
    57. }
    58. $capsule->bootEloquent();
    59. }
    60. }