phalcon:跟踪sql语句

phalcon没有像yii那些框架一样内置trace工具,所以我们只能自己搞。

在phalcon里有一个\Phalcon\Db\Profiler 类,这个类可以用来记录sql语句并计算消耗的时间。

那么如何使用它呢?

手册里其实已经提供了方法,总结如下:

1.向$di里注册profiler服务

?
1
2
3
$di ->set( 'profiler' , function (){
     return new \Phalcon\Db\Profiler();
}, true);



2.注册db服务时,顺便注册下事件 
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
$di ->set( 'db' , function () use ( $di ) {
     //新建一个事件管理器
     $eventsManager = new \Phalcon\Events\Manager();
 
     //从di中获取共享的profiler实例
     $profiler = $di ->getProfiler();
 
     //监听所有的db事件
     $eventsManager ->attach( 'db' , function ( $event , $connection ) use ( $profiler ) {
         //一条语句查询之前事件,profiler开始记录sql语句
         if ( $event -> getType () == 'beforeQuery' ) {
             $profiler ->startProfile( $connection ->getSQLStatement());
         }
         //一条语句查询结束,结束本次记录,记录结果会保存在profiler对象中
         if ( $event -> getType () == 'afterQuery' ) {
             $profiler ->stopProfile();
         }
     });
 
     $connection = new \Phalcon\Db\Adapter\Pdo\Mysql( array (
         "host" => "localhost" ,
         "username" => "root" ,
         "password" => "secret" ,
         "dbname" => "invo"
     ));
 
     //将事件管理器绑定到db实例中
     $connection ->setEventsManager( $eventsManager );
 
     return $connection ;
});



3.程序中调出sql记录

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//执行一些查询
Robots::find();
Robots::find( array ( "order" => "name" ));
Robots::find( array ( "limit" => 30));
 
//获取所有的prifler记录结果,这是一个数组,每条记录对应一个sql语句
$profiles = $this ->di->get( 'profiler' )->getProfiles();
//遍历输出
foreach ( $profiles as $profile ) {
    echo "SQL语句: " , $profile ->getSQLStatement(), "\n" ;
    echo "开始时间: " , $profile ->getInitialTime(), "\n" ;
    echo "结束时间: " , $profile ->getFinalTime(), "\n" ;
    echo "消耗时间: " , $profile ->getTotalElapsedSeconds(), "\n" ;
}
 
//直接获取最后一条sql语句
echo $this ->di->get( 'profiler' )->getLastProfile()->getSQLStatement();


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值