Working with objects - Component overview - Db - Using event listeners.php 2.14 KB
Newer Older
1

hansbrix's avatar
hansbrix committed
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
Doctrine_Db has a pluggable event listener architecture. It provides before and after
listeners for all relevant methods. Every listener method takes one parameter: a Doctrine_Db_Event object, which
holds info about the occurred event.



Every listener object must either implement the Doctrine_Db_EventListener_Interface or Doctrine_Overloadable interface. 
Using Doctrine_Overloadable interface
only requires you to implement __call() which is then used for listening all the events.  


<?php

$str = "<?php
class OutputLogger extends Doctrine_Overloadable {
    public function __call(\$m, \$a) {
        print \$m . ' called!';
    }
}
?>";
renderCode($str);
?>



For convience
you may want to make your listener class extend Doctrine_Db_EventListener which has empty listener methods, hence allowing you not to define
all the listener methods by hand. The following listener, 'MyLogger', is used for listening only onPreQuery and onQuery methods.


<?php
$str = "<?php
class MyLogger extends Doctrine_Db_EventListener {
    public function onPreQuery(Doctrine_Db_Event \$event) {
        print 'database is going to be queried!';
    }
    public function onQuery(Doctrine_Db_Event \$event) {
        print 'executed: ' . \$event->getQuery();
    }
}
?>";
renderCode($str);
?>



Now the next thing we need to do is bind the eventlistener objects to our database handler.




<code type="php">

// using PDO dsn for connecting sqlite memory table

$dbh = Doctrine_Db::getConnection('sqlite::memory:');

class MyLogger extends Doctrine_Db_EventListener {
    public function onPreQuery(Doctrine_Db_Event $event) {
        print "database is going to be queried!";
    }
    public function onQuery(Doctrine_Db_Event $event) {
        print "executed: " . $event->getQuery();
    }
}

$dbh->setListener(new MyLogger());

$dbh->query("SELECT * FROM foo"); 
// prints:
// database is going to be queried
// executed: SELECT * FROM foo


class MyLogger2 extends Doctrine_Overloadable {
    public function __call($m, $a) {
        print $m." called!";
    }
}

$dbh->setListener(new MyLogger2());

$dbh->exec("DELETE FROM foo");
// prints:
// onPreExec called!
// onExec called!
</code>