We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Adding db event

I want to add logging for my db queries and follow the example from the docs: https://docs.phalcon.io/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? https://docs.phalcon.io/en/latest/reference/db.html#database-events



2.6k

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

$db->execute();


98.9k

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);