We are moving our forum in GitHub Discussions. For questions about Phalcon v3/v4 you can visit here and for Phalcon v5 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


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



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