php事件系统实现

发布时间:2022-04-30 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了php事件系统实现脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
我想在我的自定义MVC框架中实现一个Event系统,以允许解耦
需要互相交流的类.基本上,任何类触发事件的能力以及侦听此事件的任何其他类都能够挂钩它.

但是,鉴于PHP的性质没有任何架构,我似乎无法找到正确的实现.

例如,假设我有一个User模型,每次更新它时,它都会触发userUpdate事件.现在,此事件对于A类(例如)很有用,因为它需要在更新用户时应用自己的逻辑.
但是,更新用户时不会加载类A,因此它无法绑定到User对象触发的任何事件.

你怎么能绕过这种情况?
错误地接近了吗?

任何想法将不胜感激

解决方法

@H_777_20@ 在触发事件之前必须有一个A类实例,因为您必须注册该事件.如果您注册静态方法,则会有例外.

假设你有一个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'));
    }
}

以及如何注册活动?假设您有方法更新的A类.

// 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,请注明来意。