Feb 17 2011

Logging queries in Doctrine 1.2

The developers of Doctrine have made the task of logging queries trivial, thanks to their event listener architecture.

One just needs to create a class which extends Doctrine_EventListener:

class QueryDebuggerListener extends Doctrine_EventListener
{
    protected $queries;

    public function preStmtExecute(Doctrine_Event $event)
    {   
        $query = $event->getQuery();
        $params = $event->getParams();

        //the below makes some naive assumptions about the queries being logged
        while (sizeof($params) > 0) {
            $param = array_shift($params); 

            if (!is_numeric($param)) {
                $param = sprintf("'%s'", $param);
            }   

            $query = substr_replace($query, $param, strpos($query, '?'), 1); 
        }   

        $this->queries[] = $query;
    }

    public function getQueries()
    {   
        return $this->queries;
    }
}

And add the event listener:

$c = Doctrine_Manager::connection($conn);
$queryDbg = new QueryDebuggerListener();
$c->addListener($queryDbg);

I like to use the above to get a feel for how many queries are being performed.

For example, I was using $foo->Bar['field'] to retrieve a field value from a relation at one point. The code can result in another query, which could be avoided by using a join on the original query for the record. See the Doctrine documentation for a clearer example.

Info

I'm Ade Slade, a PHP web developer.