phalcon:跟踪sql语句
phalcon沒有像yii那些框架一樣內置trace工具,所以我們只能自己搞。
在phalcon里有一個\Phalcon\Db\Profiler 類,這個類可以用來記錄sql語句并計算消耗的時間。
那么如何使用它呢?
手冊里其實已經提供了方法,總結如下:
1.向$di里注冊profiler服務
$di->set('profiler', function(){
return new \Phalcon\Db\Profiler();
}, true);
2.注冊db服務時,順便注冊下事件
$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記錄
//執行一些查詢
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();
總結
以上是生活随笔為你收集整理的phalcon:跟踪sql语句的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 尝鲜 workerize 源码
- 下一篇: git 本地代码到github(转)