Adding db event

I want to add logging for my db queries and follow the example from the docs: http://docs.phalconphp.com/en/latest/reference/models.html#logging-low-level-sql-statements

It works for $db->query() but not $db->execute(). Can I extend the existing db events? http://docs.phalconphp.com/en/latest/reference/db.html#database-events



2.2k

Or is this a possible bug? Should this fire the before and afterQuery event?

$db->execute();


91.3k

It must work, there is unit-tests for it:

https://github.com/phalcon/cphalcon/blob/master/unit-tests/DbProfilerTest.php#L120 https://github.com/phalcon/cphalcon/blob/master/unit-tests/DbProfilerTest.php#L52 https://github.com/phalcon/cphalcon/blob/master/unit-tests/DbProfilerTest.php#L57

Follow this example:

$connection = new Mysql(array(
    "host"     => 'localhost',
    "username" => 'root',
    "password" => 'pass',
    "dbname"   => 'test'
));

$eventsManager = new Phalcon\Events\Manager();

$logger = new \Phalcon\Logger\Adapter\File(APP_PATH . "/app/logs/db.log");

//Listen all the database events
$eventsManager->attach('db', function($event, $connection) use ($logger) {
   if ($event->getType() == 'beforeQuery') {
        $sqlVariables = $connection->getSQLVariables();
        if (count($sqlVariables)) {
            $logger->log($connection->getSQLStatement() . ' ' . join(', ', $sqlVariables), Logger::INFO);
        } else {
            $logger->log($connection->getSQLStatement(), Logger::INFO);
        }
    }
});

//Assign the eventsManager to the db adapter instance
$connection->setEventsManager($eventsManager);