I checked out the cookbook article on evens and behaviors. Can someone clarify if I have it right…
Events operate on objects.
Models represent objects.
Events can be tied to models so that when a query returns an array of objects, you can raise various events for each of them?
So let’s say I have a document object and I want to add an event handler that allows the document to delete itself. But also, the document has related data in other tables so the cleanup is more than just a delete().
The handler would contain all the cleanup code and then a ‘$this->delete()’ ?
I could just call a function in the model class (or any other class) that does the same thing.
Obviously I’m not understanding the proper use of events.
I find the cookbook article a little confusing because it shows assignment to onSomethingGoesOn (the array of registered event handlers), as well as calls to the method onSomethingGoesOn (with an event data object as parameter). The method onSomethingGoesOn is needed to define the event name but it also contains an actual call to raiseEvent(). That means you can choose to call the method onSomethingGoesOn() instead of calling raiseEvent() directly.
The framework defines the following events:
public function onBeginRequest($event)
public function onEndRequest($event)
public function onAfterConstruct($event)
public function onAfterFind($event)
public function onBeforeValidate($event)
public function onAfterValidate($event)
public function onBeforeSave($event)
public function onAfterSave($event)
public function onBeforeDelete($event)
public function onAfterDelete($event)
public function onException($event)
public function onError($event)
That will give you an idea what it could be used for. If you want to be notified when such an event occurs you subscribe to it by registering an event handler (callback). There’s also a corresponding function beforeValidate(), beforeSave() etc. that can be overriden. The base class implementation is the one that in fact raises the corresponding event.
I can’t give a good example right now, of potential useful custom events in an Yii application (lifetime: web request cycle). It probably could be some detected condition that you want other parts of the application to act upon.
In an embedded or desktop environment it would be all sorts of asynchronuous stimuli like timer tick, serial data available, user pressing a key or moving a slider.
As for behaviors, they "patch in" additional methods and can contain and register event handlers as well.
Thank you, Tommy. That puts the practical scope to it.