[Solar-talk] Event Handler simplest implementation

Travis Swicegood development at domain51.com
Sun Nov 26 07:20:10 PST 2006


Rodrigo Moraes wrote:
> I replaced my Pear::Event_Dispatcher port by the simplest
> implementation I could forge for a event handler:
>
> http://solarphp.org/wiki/proposals/Events
>
> It's useful enough like it is, and I've been adding hooks to my app
> and I think that the concept is fantastic. You end up with decoupled
> but "hookable" objects and I believe there are many places where this
> could be very useful in Solar.
>
> Do you think it could be simple like this or do you have something else in mind?

I can do one simpler for you:

<?php

// detested prototype code (i.e., hasn't been tested)
class Solar_EventHandler extends Solar_Base
{
    private $_events = array();
    public function register($event, $callable)
    {
       if (!is_callable($callable)) {
          throw $this->_exception('ERR_NONCALLABLE_CALLBACK');
       }
       $this->_events[$event][] = $callable;
    }

    public function notify($event, $object)
    {
       if (!isset($this->_events[$event])) {
          return;
       }
       foreach ($this->_events[$event] as $observer) {
          call_user_func($observer, $object);
       }
    }
}

?>

Now your callbacks can be anything without having to implement a 
specific method API - just something that's callable (functions, objects 
that act like functions (i.e., static methods), real objects, etc.).  
You'll note that I'm passing in $object - I'd make the default behavior 
to be pass the object that's calling the notification as your parameter 
so the observing object would have access to whatever triggered the 
event and could use/modify it.

-Travis


More information about the solar-talk mailing list