Events Vs Methods


I tried to understand events but it’s quite difficult. Because of that I have few questions.

  1. How raising event is better than just simply calling method from another class which could have attached to this event?

  2. When I want to add event to CActiveRecord where should I attach handlers for it?

An event allows loose coupling: the method that you call can or can not be there: the method generating the event (or the method call) does not have to know it is there.

Events allow more flexibility: you can add and remove functionnality without changing the calling method and this can depend on your context/scenario.

This also allows behaviors to act on events from the owner class.

Events allow reuse (see behaviors for instance).

However, events have some overhead.

The place where you attach handlers likely depends on what the handlers do. You may attach some handlers in the ActiveRecords, in ActiveRecord behaviors, … .