Working with objects - Component overview - Db - Chaining listeners.php 1 KB
Newer Older
hansbrix's avatar
hansbrix committed
1 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
Doctrine_Db supports event listener chaining. It means multiple listeners can be attached for 
listening the events of a single instance of Doctrine_Db. 



For example you might want to add different aspects to your Doctrine_Db instance on-demand. These aspects may include
caching, query profiling etc.





<code type="php">

// using PDO dsn for connecting sqlite memory table

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

class Counter extends Doctrine_Db_EventListener {
    private $queries = 0;

    public function onQuery(Doctrine_Db_Event $event) {
        $this->queries++;
    }
    public function count() {
        return count($this->queries);
    }
}
class OutputLogger extends Doctrine_Overloadable {
    public function __call($m, $a) {
        print $m." called!";
    }
}
$counter = new Counter();

$dbh->addListener($counter);
$dbh->addListener(new OutputLogger());

$dbh->query("SELECT * FROM foo"); 
// prints:
// onPreQuery called!
// onQuery called!

print $counter->count(); // 1

</code>