zoukankan      html  css  js  c++  java
  • phalcon:跟踪sql语句

    在phalcon里有一个PhalconDbProfiler 类,这个类可以用来记录sql语句并计算消耗的时间。那么如何使用它呢?

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

    1.向$di里注册profiler服务

    $di->set('profiler', function(){
        return newPhalconDbProfiler();
    }, true);

    2.注册db服务时,顺便注册下事件 

    $di->set('db', function() use ($di) {
        //新建一个事件管理器
        $eventsManager = new PhalconEventsManager();
     
        //从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 PhalconDbAdapterPdoMysql(array(
            "host" => "localhost",
            "username" => "root",
            "password" => "secret",
            "dbname" => "invo"
        ));
     
        //将事件管理器绑定到db实例中
        $connection->setEventsManager($eventsManager);
     
        return $connection;
    }); 

    3.程序中调出sql记录

    //执行一些查询
    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(), "
    ";
       echo "开始时间: ", $profile->getInitialTime(), "
    ";
       echo "结束时间: ", $profile->getFinalTime(), "
    ";
       echo "消耗时间: ", $profile->getTotalElapsedSeconds(), "
    ";
    }
     
    //直接获取最后一条sql语句
    echo $this->di->get('profiler')->getLastProfile()->getSQLStatement();
  • 相关阅读:
    webpack进阶(二)
    webpack的loader和plugin的区别
    接口和面向接口编程
    设计原则与编程技巧汇总
    W3C的盒子模型和IE的盒子模型
    React的组件
    React的路由react-router
    三种编程命名规则:驼峰命名法,帕斯卡命名法,匈牙利命名法
    gulp 构建 demo
    antd 表单的两种校验方式
  • 原文地址:https://www.cnblogs.com/dormscript/p/4787650.html
Copyright © 2011-2022 走看看