0

i am just playing around with php to create a plugin architecture. for this i am using the event listener ( mediator ) pattern where a code can listen/fire an event.

my real question is how do i make the listener object available through out the application.' THe only solutions i can think of right now are making the core listener / observer class singleteon so any code from anywhere can register a listener.

$listener = Plugin::getInstance();
$listener->addEventListener('savePost', ....);

and for firing also i can use the same process.

OR

making only the registered event array static for example

private static $registeredEvents = array();
public function addEventListener($eventName, Closure $c){         
     self::$registeredEvents[$eventName] = $c;
}

If i do this no matter how the plugin/listener object is provided to any client code the same container ( $registeredEvents ) will be used.

Otherwise providing new instances of the listener class to other objects results in having dispersed registered events. So when firing specific events from the system, i cannot loop through each and every registered events from different instances.

So plz anyone show me more efficient way of doing this.

themightysapien
  • 8,309
  • 2
  • 17
  • 15

1 Answers1

0

Singleton Class & Static $registeredEvents is a good way to do this You are not loading the memory as you only use the static instance and the static registeredEvents which are allocated only one.

In PHP when you work with objects you actually work with the pointers of those objects

You can also use a registry (such as Zend_Registry) and keep the one and only instance in the registry

Sample:

$registry = Zend_Registry::getInstance();
$registry->set('listener', $listener); // or
// $registry->listener = $listener;

For loading you will use:

// $registry = Zend_Registry::getInstance(); // if needed
$registry->listener->addEventListener();

You can also make the function static, and you don't even need to instantiate, you only use:

My_Listener_Class::addEventListener();

For more ideas consider checking this question:

http://stackoverflow.com/questions/42/best-way-to-allow-plugins-for-a-php-application

It might help you. It contains some good ways to integrate plugins within php.

Gabi Dj
  • 645
  • 6
  • 15