Last active
August 29, 2015 13:57
-
-
Save kitelife/9612977 to your computer and use it in GitHub Desktop.
观察者模式
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 | |
| /* | |
| 观察者模式的核心在于允许你的应用程序注册一个回调,当某个特定的事件发生时便会触发它。 | |
| */ | |
| class Event { | |
| static protected $callbacks = array(); | |
| static public function registerCallback($eventName, $callback) | |
| { | |
| if (!is_callable($callback)) { | |
| throw new Exception("Invalid callback!"); | |
| } | |
| $eventName = strtolower($eventName); | |
| self::$callbacks[$eventName][] = $callback; | |
| } | |
| static public function trigger($eventName, $data) | |
| { | |
| $eventName = strtolower($eventName); | |
| if (isset(self::$callback[$eventName])) { | |
| foreach(self::$callbacks[$eventName] as $callback) { | |
| // The callback is either a closure, or an object that defines __invoke() | |
| $callback($data); | |
| } | |
| } | |
| } | |
| } | |
| class MyDataRecord { | |
| public function save() | |
| { | |
| // Actually save data here | |
| // Trigger the save event | |
| Event::trigger('save', array("Hello", "World")); | |
| } | |
| } | |
| class LogCallback { | |
| public function __invoke($data) | |
| { | |
| echo "Log Data" . PHP_EOL; | |
| var_dump($data); | |
| } | |
| } | |
| Event::registerCallback('save', new LogCallback()); | |
| Event::registerCallbacl('save', function ($data) { | |
| echo "Clear Cache" . PHP_EOL; | |
| var_dump($data); | |
| }); | |
| $data = new MyDataRecord(); | |
| $data->save(); // 'save' Event is triggered here |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment