Thursday, March 18, 2010

Events & Behaviors in Yii - Initial Notes

This one is a work in progress as I try to figure out how to use this aspect correctly. This are my "notes" from reading these documents.

I'm basing this on the following two document references:
http://www.yiiframework.com/doc/cookbook/44
http://www.yiiframework.com/doc/guide/basics.component (section on events)

Key Points

  • Events:

    • Event handlers are special properties that take methods as their values
    • Attaching a method to an event will cause the method to be invoked automatically where the event is raised
    • Event names are case-insensitive
    • Use "on" methods to define events for the component
    • ex: $this->onClicked = $callback
    • public function onClicked($event){ $this->raiseEvent('onClicked', $event); }
    • callback can be a global function or a class method, or an anonymous function. If a class method, pass as array($object,'methodName')
  • Behaviors

    • Behaviors are 'mixin's (interface with implemented methods -- included instead of inherited)
    • The Behavior class defines several functions or properties which then can be added to another class by attaching the behavior to the class

Questions:

  • Not sure what this means:

    "An event can be attached with multiple handlers."
    Does that mean that I can have multiple onClick assignments on the same object, or onClick assignments on multiple objects which will then all process the same event.
    Follow up: The Cookbook says you can attach multiple functions to the same object handle and they will be processed in the order in which they were added -- this will require testing ;)

Additional Referenced Reading

1 comment:

  1. Dear Danaluther,
    I read your post on your blog, and I am also reading the Yii cookbook you mentioned above. I am tring to figure out the usage of callback in Yii and though I have undertand the basic functionality of it (what it does), but failed to understand the real hood behind the scene (how it does). Really odd when I read the code like this:

    $Mycomponent->onClick = someFunction().

    I know it attaches a handler - someFunction() - to onClick event, but could you tell me what kind of syntax of this code using? It's not any callback examples on PHP.net that I have seen. Thank you!

    ReplyDelete