如何将PHP DebugBar与MySQLI集成并记录数据库查询?
用PHP DebugBar记录MySQLi查询的实现方案
当然可行,PHP DebugBar本身没有官方提供MySQLi收集器,但可以通过自定义包装类来捕获查询操作并上报给DebugBar,下面是具体实现步骤:
1. 自定义MySQLi包装类
创建一个继承自原生mysqli的类,重写执行查询的核心方法,在方法内记录查询的SQL、执行时间、错误信息等,再传递给DebugBar的收集器(可以复用PDOCollector的逻辑,也能自定义收集器)。
示例代码:
use DebugBar\DebugBar; use DebugBar\DataCollector\PDO\PDOCollector; class DebugMySQLi extends mysqli { private $debugBar; private $queryCollector; public function __construct($host, $user, $pass, $db, $port = null, $socket = null) { parent::__construct($host, $user, $pass, $db, $port, $socket); // 初始化DebugBar与查询收集器 $this->debugBar = DebugBar::create(); $this->queryCollector = new PDOCollector(); $this->debugBar->addCollector($this->queryCollector); } // 重写普通查询方法 public function query($query, $resultmode = MYSQLI_STORE_RESULT) { $startTime = microtime(true); $result = parent::query($query, $resultmode); $duration = microtime(true) - $startTime; // 将查询信息提交给收集器 $this->queryCollector->addQuery($query, [], $duration, $this->errno, $this->error); return $result; } // 重写预处理语句方法,包装Statement public function prepare($query, $options = null) { $stmt = parent::prepare($query, $options); if ($stmt) { $stmt = new DebugMySQLiStmt($stmt, $query, $this->queryCollector); } return $stmt; } // 获取DebugBar实例,用于渲染 public function getDebugBar() { return $this->debugBar; } } // 包装MySQLi Statement,捕获预处理查询的执行 class DebugMySQLiStmt extends mysqli_stmt { private $rawQuery; private $collector; public function __construct(mysqli_stmt $stmt, $query, $collector) { $this->rawQuery = $query; $this->collector = $collector; parent::__construct($stmt->get_connection()); // 复制原Statement的属性(确保功能正常) foreach (get_object_vars($stmt) as $prop => $value) { $this->$prop = $value; } } public function execute($params = null) { $startTime = microtime(true); $result = parent::execute($params); $duration = microtime(true) - $startTime; // 记录预处理查询与参数 $this->collector->addQuery($this->rawQuery, $params ?: [], $duration, $this->errno, $this->error); return $result; } }
2. 替换原生MySQLi连接
在业务代码中,使用自定义的DebugMySQLi类代替原生mysqli创建数据库连接:
$db = new DebugMySQLi('localhost', 'your_username', 'your_password', 'your_database');
3. 渲染DebugBar
在页面输出的末尾,添加DebugBar的渲染代码,就能在页面看到收集到的MySQLi查询信息了:
echo $db->getDebugBar()->getJavascriptRenderer()->render();
额外说明
- 如果需要更定制化的收集逻辑,可以自己实现
DataCollectorInterface,创建专属的MySQLiCollector类,定义自己的收集规则和展示格式。 - 确保所有数据库操作都通过这个自定义类执行,否则无法捕获未经过包装的查询。
内容的提问来源于stack exchange,提问作者Sirkow
相关产品推荐
相关产品推荐

