Search code examples
phpdesign-patternsobserver-pattern

Observer Pattern Logic Without OOP?


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 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


Solution

  • 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.
      }
    }