views:

73

answers:

3

Hi Stackoverflow,

I was thinking about implementing a logic similar to observer pattern on my website, for implementing hooks.

What I am looking for is something similar to this http://stackoverflow.com/questions/42/best-way-to-allow-plugins-for-a-php-application

However the code there is too limited, as I cant attach multiple hooks to same listener.

I am clueless about how to amplify that code to make it able to listen multiple actions at one event.

Thank You

A: 

Simply add a ' * ' hook, and modify the hook() function to call all the 'hooks' in both the named event and the ' * ' event.

Then, simply do:

add_listener('*', 'mycallback');
ircmaxell
Hi mate, I didnt understand this ?
atif089
Basically, create a new hook identified by ` * `. Then, edit the `hook()` function to call all those listeners as well as the ones for the name specified...
ircmaxell
A: 

Take a look at Spl_Observer.

You said you didn't want OOP, but you can easily implement a non-OOP wrapper around this.

Artefacto
+1  A: 

You can do as ircmaxell suggests: add hooks. But clearly, the information he gave was not enough for you.

If you like learning by example, you may look at the CMS Drupal, wich is not OOP, but uses the observer pattern, called hooks all over the place to allow a modular design.

A hook works as follows:

  • a piece of php looks for the existence of a specially named function.
  • If that exists, call it and use its output (or do nothing with it)

For example:

  • Just before an article gets saved in Drupal, the article-system calls the hook_insert
  • Every module that has a function in the name of ModuleName_insert, will see that function being called. Example: pirate.module may have a function pirate_insert(). The article system makes a roundtrip along all the modules and sees if ModuleName_insert exists. It will pass by pirate module and finds pirate_insert(). It will then call that function (and pass some arguments along too). As such, allowing the pirate.module to change the article just before insertation (or fire some actions, such as turning the body-text into pirate-speek).

The magic happens in so called user_callbacks. An example:

$hook = 'insert'
foreach (module_implements($hook) as $module) {
  $function = $module .'_'. $hook;
  $result = call_user_func_array($function, $args);
}

And the function module_implements might look something like:

$list = module_list(FALSE, TRUE, $sort); //looks for files that are considered "modules" or "addons".
foreach ($list as $module) {
  if (function_exists($module.'_'.$hook)) { //see if the module has the hook 'registered'
    $implementations[$hook][] = $module; //if so: add it to a list with functions to be called.
  }
}
berkes