脚本宝典收集整理的这篇文章主要介绍了php事件系统实现,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
但是,鉴于PHP的性质没有任何架构,我似乎无法找到正确的实现.
例如,假设我有一个User模型,每次更新它时,它都会触发userUpdate事件.现在,此事件对于A类(例如)很有用,因为它需要在更新用户时应用自己的逻辑.
但是,更新用户时不会加载类A,因此它无法绑定到User对象触发的任何事件.
你怎么能绕过这种情况?
我错误地接近了吗?
任何想法将不胜感激
假设你有一个User类,它应该触发一个事件.首先,您需要一个(抽象)事件调度程序类.这种事件系统的工作方式与ActionScript3类似:
abstract class Dispatcher { PRotected $_listeners = array(); public function addEventListener($tyPE,callable $listener) { // fill $_listeners array $this->_listeners[$type][] = $listener; } public function dispatchEvent(Event $event) { // call all listeners and send the event to the callable's if ($this->hasEventListener($event->getType())) { $listeners = $this->_listeners[$event->getType()]; foreach ($listeners as $callable) { call_user_func($callable,$event); } } } public function hasEventListener($type) { return (isset($this->_listeners[$type])); } }
您的User类现在可以扩展该Dispatcher:
class User extends Dispatcher { function update() { // do your update LOGic // trigger the event $this->dispatchEvent(new Event('User_update')); } }
// non static method $classA = new A(); $user = new User(); $user->addEventListener('User_update',array($classA,'update')); // the method update is static $user = new User(); $user->addEventListener('User_update',array('A','update'));
如果您有适当的自动加载,则可以调用静态方法.在这两种情况下,Event都将作为参数发送到update方法.如果你愿意,你也可以有一个抽象的Event类.
以上是脚本宝典为你收集整理的php事件系统实现全部内容,希望文章能够帮你解决php事件系统实现所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。