Php event system implementation

I would like to implement an Event system in my custom MVC framework to allow the decoupling of classes that must interact with each other. In principle, the ability of any class to trigger an event and any other class that listens so that this event can connect to it.

However, I cannot find the correct implementation, given that the nature of php has nothing architecture.

For example, let's say that I have a User model that each time it is updated fires the userUpdate event. Now this event is useful for class A (for example), since it requires the use of its own logic when updating the user. However, class A does not load when the user is updated, so he cannot communicate with events raised by the User object.

How can you get around this scenario? I'm not wrong?

Any ideas would be highly appreciated

+4
source share
2 answers

There must be an instance of class A before the event, because you must register for this event. An exception would be if you registered a static method.

, 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]));
    }
}

:

class User extends Dispatcher
{
    function update()
    {
        // do your update logic

        // trigger the event
        $this->dispatchEvent(new Event('User_update'));
    }
}

? , A 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.

+5
0

All Articles