Skip to content

Instantly share code, notes, and snippets.

@hans-d
Created June 15, 2012 22:13
Show Gist options
  • Select an option

  • Save hans-d/2938963 to your computer and use it in GitHub Desktop.

Select an option

Save hans-d/2938963 to your computer and use it in GitHub Desktop.

Revisions

  1. hans-d created this gist Jun 15, 2012.
    75 changes: 75 additions & 0 deletions gistfile1.aw
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,75 @@
    <?php

    namespace app\extensions\action;

    /**
    * Observer for the Observer pattern. When a subject sends a notification for an event,
    * the registered listeners can act upon it.
    *
    * @author hdonner
    *
    */
    class Observers extends \lithium\core\StaticObject {

    /**
    * The registered listeners per event
    *
    * @var array
    */
    protected static $_listeners = array();

    /**
    * Adds a listener for the given event.
    *
    * @param string $event
    * @param callable $callable the callback to be used
    */
    public static function add($event, $callable) {
    if (!isset(static::$_listeners[$event])) {
    static::$_listeners[$event] = array();
    }
    return static::$_listeners[$event][] = $callable;
    }

    /**
    * Gets a list of registered events, or a list of listeners for a
    * specific event.
    *
    * @param string $name `null` to get a list of all events, or the event name
    * @return mixed
    */
    public static function get($event = null) {
    if (!$event) {
    return array_keys(static::$_listeners);
    }
    if (!isset(static::$_listeners[$event])) {
    return null;
    }
    return static::$_listeners[$event];
    }

    /**
    * Called by a subject to notify the listeners of an event.
    *
    * For each notification, the callbacks of all the listeners for that
    * event a called with the specified arguments.
    *
    * @param string $event name of the event
    * @param array $args arguments to pass
    */
    public static function notify($event, $args=array()) {
    if (isset(static::$_listeners[$event])) {
    foreach (static::$_listeners[$event] as $listener) {
    $listener($args);
    }
    }
    }

    /**
    * Resets all the listeners to zero.
    */
    public static function reset() {
    static::$_listeners = array();
    }

    }