As with many frameworks and programming languages, Yii provides an event system which is very easy to use and extended. Event can be described as a special occurrence in the execution flow of an application. For instance when a mouse is clicked or pressed, when a user posts a comment or withdraws from his account.

An event object encapsulates the information about the event. For a mouse click, it could provide the button (left or right) which was clicked. The type of information this object carries vary according to how it is implemented.

The main event object in Yii event handling system is CEvent. It encapsulates the parameters associated with an event. At the minimum, it contains the information about who raised the event. The sender property describes who raises the event and the handled property indicates if the event is handled. If an event handler sets handled to true, those handlers that are not invoked yet will not be invoked anymore.

The event objects are created at the time the event occurs. For instance, when an active record is deleted, an event of the type ‘onDelete’ occurrs. The framework creates the event object and passes the model which was deleted as parameter to raiseEvent(name.eventObject). Event handlers will then be notified.

The code below could be a minimal implementation of the delete method of active record.

public function delete(){
    //execute the necessary sql
    $event = new CEvent($this);
    $this->raiseEvent('onDelete',$event);
}

There are times when the information carried by the event object is not enough for the work at hand. Extending the base CEvent class then becomes necessary. Suppose in your web application, you would like to log information about how much a user withdrew from his account and the time it happened, you are not going to get the information from the CEvent object. This calls for your own event object which is capable of providing such information to event handlers.

The event object we are going to create is called WithdrawEvent. It will provide information about the time the amount was withdraw, the actual amount withdrawn and the generator of the event. It will extend the CEvent class.

class WithrawEvent extend CEvent{
    public $amount;
    public $time;

    public function __construct($sender, $amount, $time){
        $this->sender = $sender;
        $this->amount = $amount;
        $this->time = $time;
    }
}

When the actual event occurs, we will create an instance and supply the necessary parameters to the event object. We will then notify the event handlers.

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