Phalcon 框架如何在model执行完毕,如何打印SQL?
本文介绍了Phalcon 框架如何在model执行完毕,如何打印SQL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
Phalcon 框架如何在model执行完毕,如何打印SQL?
$where = [
'conditions' => "stat_date BETWEEN :start_stat_date: AND :end_stat_date:",
'bind' => [
'start_stat_date' =>date('Y-m-d', strtotime('-1 day')),
'end_stat_date' => date('Y-m-d', strtotime('-7 day')),
],
'columns'=>'sum(day_reg_act_parent_num) AS count',
];
$user = $model->findFirst($where);
如何打印出上面语句最后构造成的SQL呢?
解决方案
在DI注册DB服务的时候,执行SQL监听事件:
use Phalcon\Db\Profiler as DbProfiler;
use Phalcon\Mvc\Model\Manager as ModelsManager;
$di -> setShared('db', function () use($config) {
$dbconfig = $config -> database -> db;
$dbconfig = $dbconfig -> toArray();
if (!is_array($dbconfig) || count($dbconfig)==0) {
throw new \Exception("the database config is error");
}
$eventsManager = new \Phalcon\Events\Manager();
// 分析底层sql性能,并记录日志
$profiler = new DbProfiler();
$eventsManager -> attach('db', function ($event, $connection) use ($profiler) {
if($event -> getType() == 'beforeQuery'){
//在sql发送到数据库前启动分析
$profiler -> startProfile($connection -> getSQLStatement());
}
if($event -> getType() == 'afterQuery'){
//在sql执行完毕后停止分析
$profiler -> stopProfile();
//获取分析结果
$profile = $profiler -> getLastProfile();
$sql = $profile->getSQLStatement();
$executeTime = $profile->getTotalElapsedSeconds();
//日志记录
$logger = \Marser\App\Core\PhalBaseLogger::getInstance();
$logger -> write_log("{$sql} {$executeTime}", 'debug');
}
});
$connection = new \Phalcon\Db\Adapter\Pdo\Mysql(array(
"host" => $dbconfig['host'], "port" => $dbconfig['port'],
"username" => $dbconfig['username'],
"password" => $dbconfig['password'],
"dbname" => $dbconfig['dbname'],
"charset" => $dbconfig['charset'])
);
/* 注册监听事件 */
$connection->setEventsManager($eventsManager);
return $connection;
});
具体参考PhalconCMS的代码:https://github.com/KevinJay/P...
这篇关于Phalcon 框架如何在model执行完毕,如何打印SQL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文