Hooks

Intent
Build a function/method from multiple components
Motivation
Very often we need to decouple or delay definitions until run time
Implementation
Implement a methods that allows executing a set of functions at predefined times
Example
class hooks {
  private $cache = array();

  function run( $func, $arg ) {
    foreach(array('before','at','after') as $hook)
      foreach($this->cache[$func][$hook] as $f) { $f($arg);  }
  }

  function hook($hook, $func, $cb) {
    $this->cache[$func][$hook][]=$cb
  }

  function before($func, $cb) {
    $this->cache[$func]['before'][]=$cb
  }
  
  function at($func, $cb) {
    $this->cache[$func]['at'][]=$cb
  }
  
  function after($func, $cb) {
    $this->cache[$func]['after'][]=$cb
  }
  
  function around($hook, $func, $cb) {
    $this->cache[$func]['around'][]=$cb
    $this->cache[$func]['after'][]=$cb
  }

}

//and usage
$hs = new hooks();
$hs->hook('before','label','before_a_func');
$hs->hook('at','label','core');
$hs->run();

//or using the individual methods
$hs = new combinator();
$hs->before('label','before_a_func');
$hs->around('label','tracer');
$hs->run();
Powered by Drupal, an open source content management system