For a given web request, there could be many events which could occur on an object. If the object must respond to multiple events, then these events become unmanageable and encapsulate too much in one place that should probably be separated.

The solution will be to create event handler objects which will be used to listen to these events. These events handler objects should be capable of registering themselves with the event generator in order to be notified.

A behavior in Yii is an object whose methods can be ‘inherited’ by the components it is attached to. A behavior object of a derived class CBehavior has a method events(). It declares events and the corresponding event handler methods. The events are defined by the 'owner' component (the component the behavior was attached to and in our case the event generator), while the handler methods by the behavior class.

The handlers will be attached to the corresponding events when the behavior is attached to the event generator object (component); and they will be detached from the events when the behavior is detached from the component.

class WithdrawBehavior extends CBehavior{
 
    public function events(){
        return array(
        'onWithdraw'=>'withdrawLog', 
        );
    } 
    public function withdrawLog($event){
        Yii::log("Amount withdrawn: {$event->amount}",'info');
        Yii::log("Time of withdrawal: {$event->time}",'info');
        Yii::log("Amount Left: {$event->sender->amount}",'info');
    }
 
}

The code above defines a class WithdrawBehavior which extends the CBehavior class. It then declares the onWithdraw event with its corresponding handler as withdrawLog. The withdrawLog method just logs some information gathered from the event parameter. For CController, CFormModel and CActiveRecord classes which will usually be extended, we can attach behaviors by overriding their behavior method.

public function behaviors(){
    return array(
        'withdraw'=>array(
            'class'=>'ext.directoryName.WithdrawBehavior'
        ),
    );
}

For CApplicationComponents, we can configure it in our configuration file.

In our model, we will define the function which will raise the event. An event of the type WithdrawEvent will be raised when a user withdraws an amount from their account. The following code is part of the model class.

public function withdraw($amount){
    $this->amount -= $amount;
    $event = new WithrawEvent($this,$amount,time());
    $this->raiseEvent('onWithdraw',$event);
}
//actual call
$model->withdraw(100);

When the 'onWithdraw' event is raised, the Yii event handling mechanism will look for a method that is supposed to handle this event. Since the events handlers from the events() method are added to the list of event listeners for the component, the corresponding handler withdrawLog which the model 'inherited' will be called.