Observer Classes

Observer Classes

Observer classes respond to life-cycle callbacks to implement trigger-like behavior outside the original class. This is a great way to reduce the clutter that normally comes when the model class is burdened with functionality that doesn't pertain to the core responsibility of the class.

Example

class CommentObserver extends AkObserver 
{ 
    function afterSave($comment) 
    { 
        Ak::mail("admin@example.com", "New comment was posted", $comment->toString()); 
    }
}

This Observer sends an email when a Comment::save is finished.

Observing a class that can't be inferred

Observers will by default be mapped to the class with which they share a name. So CommentObserver will be tied to observing Comment, ProductManagerObserver to ProductManager, and so on. If you want to name your observer differently than the class you're interested in observing, you can use the AkActiveRecord→observe() class method:

function afterUpdate(&$account) 
{ 
    $AuditTrail =& new AuditTrail($account, "UPDATED"); $AuditTrail->save(); 
}

If the audit observer needs to watch more than one kind of object, this can be specified with multiple arguments:

function afterUpdate(&$record) 
{ 
    $ObservedRecord =& new AuditTrail($record, "UPDATED"); $ObservedRecord->save(); 
}

The AuditObserver will now act on both updates to Account and Balance by treating them both as records.

Available callback methods

The observer can implement callback methods for each of these methods:

  • beforeCreate
  • beforeValidation
  • beforeValidationOnCreate
  • beforeSave
  • afterValidation
  • afterValidationOnCreate
  • afterCreate
  • afterSave

Triggering Observers

In order to activate an observer, you need to create an Observer instance and attach it to a model. In the Akelos Framework, this can be done in controllers using something like this:

$ComentObserverInstance =& new CommentObserver(); 
$Model->addObserver(&$ComentObserverInstance);
 
observers.txt · Last modified: 2008/09/13 23:10 by 82.103.221.224
 

The Akelos Framework was created by Bermi Ferrer and other contributors.
Potions of the code and documentation have been ported from Ruby on Rails.

The Akelos Framework is released under the LGPL license.

"Akelos", "Akelos Framework", and the Akelos logo are trademarks of Bermi Labs All rights reserved.

Wiki driven by DokuWiki