Discover Event Details Within Handler

I am trying to learn how to discover which event (eg, onBeforeSave, onAfterSave etc.) was fired from within the scope of the handler.

ie




class Handler

{

    public function handleAllEvents(CEvent $event)

    {

        // How do i know what event happened here? 

        // I inspected the $event->params , they are NULL

    }

}




class SomeModel extends CActiveRecord

{ }


$model = new SomeModel();

$eventHandler = new Handler();


// Attach to all events (In my code I actually use Reflection to discover all the 'onXX' event functions)

$model->onBeforeSave = array($eventHandler, 'handleAllEvents');

$model->onAfterSave = array($eventHandler, 'handleAllEvents');

$model->onBeforeDelete = array($eventHandler, 'onBeforeDelete');

$model->onAfterDelete = array($eventHandler, 'onAfterDelete');

// ... All events


// Fire event

$model->onAfterSave(new CEvent($model)); 



For reference: the CActiveRecord::beforeSave() code is as follows:




protected function beforeSave()

{

	if($this->hasEventHandler('onBeforeSave'))

	{

		$event=new CModelEvent($this);

		$this->onBeforeSave($event);

		return $event->isValid;

	}

	else

			return true;

}



Why don’t you override beforeSave on you CActiveRecord’s subclass?

The hope was to create a behavior that would use reflection to determine and hook into all events on an object.




// Kinda like this:

class SomeBehavior

{

    public function attach($component)

    {

        $this->component = $component;

        // use reflection to attach to all events

        foreach ($this->determineEvents($component) as $event) {

            $component->attachEventHandler($event, array($this, 'handle'.ucfirst($eventName)));

        }

    }


    //    use __call to effectively have a "handleOnBeforeSave" or "handleOnSomeUnforseenNewEvent"

    public function __call($name, $args)

    {

        if (strpos($name, 'handle') !== false) {

            $this->doSomethingWith($name, $args);

        }   

    }

}



Have a look at my event interceptor. It’s not a behavior itself, but it should be easy to re-use it in behaviors, if that’s the plce where you want to handle the events. Not sure if it is exactly what you’re looking for, but at least it can serve as an example.

Extension: http://www.yiiframework.com/extension/event-interceptor

Or on GitHub: https://github.com/bwoester/yii-event-interceptor

Hmm that is an interesting solution. Unfortunately I had to move on (employers like projects to move fwd) . Hopefully it helps someone else.

I ended up creating a handler for each event I was interested in, will have to do more work if new events crop up.