Created
June 15, 2012 22:13
-
-
Save hans-d/2938963 to your computer and use it in GitHub Desktop.
observer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment