Last Updated: October 11, 2018
·
2.95K
· elericuz

Profiling queries in Zend Framework

Sometimes you need to store all or some queries for debugging porpuses. Let's think you will store them into the your database so you could create a main controller where the rest hereby to do that or better yet, I guess, you could create a ZF Plugin, so let's see how it works!

<?php
class My_Plugin_Profiler extends Zend_Controller_Plugin_Abstract
{
  public function postDispatch()
  {
    $db = Zend_Registry::get('db');
    $profiler = $db->getProfiler();

    // we set the filter
    $profiler->setFilterQueryType(
                        Zend_Db_Profiler::SELECT |
                        Zend_Db_Profiler::INSERT |
                        Zend_Db_Profiler::UPDATE |
                        Zend_Db_Profiler::DELETE);

    $profile = $profiler->getQueryProfiles(
                        Zend_Db_Profiler::INSERT |
                        Zend_Db_Profiler::UPDATE |
                        Zend_Db_Profiler::DELETE);    

    $logs = new Logs_Model_DbTable_Log();

     /* if the filter has no content the is null 
         otherwise it will be an array and we have
         to prevent if to get no error here */
     if(is_array($profile))
     {
          foreach($profile as $row)
          {
              $data = array(
                  'sql' => $row->getQuery(),
                  'bind_params' => implode(', ', $row->getQueryParams()),
              );
              $logs->insert($data);
          }
     }
  }
}
?>

In the code above I filter select, insert, update and delete queries but then I get just the insert, update and delete.

Of course it's necessary to register this plugin to this work and since we are using the postDispatch() function we make sure that every query is going to be store at the end of the dispatch.