Last active
September 11, 2018 09:28
-
-
Save fillano/d7c5a2cef9d5e824db1171ab6d13242b to your computer and use it in GitHub Desktop.
a simple event facilities test.
This file contains 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 | |
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); | |
} | |
} | |
public static function Unregist($eventName, Callable $callback) { | |
$key = array_search($callback, self::$events[$eventName]); | |
if($key != false) { | |
array_splice(self::$events[$eventName], $key, 1); | |
} | |
} | |
} | |
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"); | |
Event::Unregist("event1", [$b, "greeting"]); | |
Event::Trigger("event1", "Hello Another World"); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment