Skip to content

Instantly share code, notes, and snippets.

@phpfiddle
Created September 11, 2018 08:29
Show Gist options
  • Save phpfiddle/a9491918a0639d5830d9ef167c825266 to your computer and use it in GitHub Desktop.
Save phpfiddle/a9491918a0639d5830d9ef167c825266 to your computer and use it in GitHub Desktop.
[ Posted by Fillano ] simple Event Facilities.
<?php
class Event {
private static $events = [];
public static function Regist($eventName, Callable $callback) {
if(!is_callable($callback)) return false;
if(!array_key_exists($eventName, self::$events)) {
self::$events[$eventName] = [];
}
self::$events[$eventName][] = $callback;
return true;
}
public static function Trigger($eventName, $eventData) {
if(!array_key_exists($eventName, self::$events)) return false;
foreach(self::$events[$eventName] as $c) {
call_user_func($c, $eventData);
}
}
}
class Test001 {
private $name;
function __construct($name) {
$this->name = $name;
}
public function greeting($data) {
echo $data . " " . $this->name . "<br>\n";
}
}
$a = new Test001("Fillano");
$b = new Test001("Hildegard");
Event::Regist("event1", [$a, "greeting"]);
Event::Regist("event1", [$b, "greeting"]);
Event::Trigger("event1", "Hello World");
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment