Search code examples
ormdoctrine-1.2php

Doctrine model instance firing record listener twice when listener is attached only once


I've a strange problem where whenever I create an instance of (say User) model and attach a record listener, the listener is invoked multiple times (overtime except for the first time). Does anyone have any clue as to why is it happening?

BTW, I'm using Doctrine in my CLI app where objects don't die off when requests are completed.


Solution

  • After digging in Doctrine source, this is what I've learned. Listeners are attached to table instance rather individual instances of model. Hence, when listener is attached to a model, it internally passes it to the table instance. Therefore, even with new instance of model if you attach fresh instance of listener, both listeners will be invoked!

    Perhaps, following example might help understanding the issue.

    // WRONG WAY
    foreach ($records as $record) {
    
        // Table returns instance of Model_User
        $model = Model_UserTable::getInstance()->make( $record );
        $listener = new Doctrine_Listener_SomeListener();
    
        // following will attach new listener for each model instance
        $model->addListener( $listener );
    
        $model->save();
    }
    

    The above will cause one listener attached to table instance for every $record. Whereas if listener should be invoked only once then here is how you need to do this.

    // RIGHT WAY
    $listener = new Doctrine_Listener_SomeListener();
    $table = Model_UserTable::getInstance();
    $table->addRecordListener( $listener ); // approach #1
    
    foreach ($records as $record) {
        $model = $table->make( $record );
        $model->addListener( $listener ); // approach #2
        $model->save();
    }
    

    N.B: Use either of the approaches