What are the correct practices for manipulating events in PHP?

7

I've created some classes and an interface to handle events for a small MVC application. My intention is to implement the Observer pattern, but I do not know if you agree, since I still confuse it with PHP. In the following code, did I do it the right way, or could it cause some maintenance problem in the future?

<?php
# Interface do listener 
interface ActionListener {
    public function actionPerformed(ActionEvent $e);
}

# O evento
class ActionEvent {

    private $eventSource;
    private $id;
    private $command;
    private $time;

    public function __construct($eventSource, $id, $command = '') {
        $this->eventSource = $eventSource;
        $this->id = $id;
        $this->command = $command;
        $this->time = time();
    }

    public function getEventSource() {
        return $this->eventSource;
    }

    public function getID() {
        return $this->id;
    }

    public function getCommand() {
        return $this->command;
    }

    public function getTime() {
        return $this->time;
    }
}

# Uma fonte de eventos.
class EventSource {

    private $listeners = [];

    public function notify($id, $command = '') {
        $event = new ActionEvent($this, $id, $command);
        foreach ($this->listeners as $actual) {
            $actual->actionPerformed($event);
        }
    }

    public function addActionListener(ActionListener $object) {
        $this->listeners[] = $object;
    }
}
    
asked by anonymous 30.12.2013 / 01:38

1 answer

2
The Design Pattern Observer (also known as Publish-Subscribe) is actually a kind of one-to-many relationship between objects, that is, when an object changes its state, dependent objects are updated.

Event-driven programming is somewhat more abstract, and can be implemented in a number of ways.

Generally, event-based technologies tend to be asynchronous, such as ReactPHP .

But assuming the question is about deploying the Design Pattern Observer, there is no official implementation of any standard, however this article might be a good starting point.

Typically, for the implementation of this pattern, we have the SplObserver classes and SplSubject of the PHP Standard Library (SPL) that are interfaces for you to implement the standard.

I recommend looking at such interfaces and comparing with your implementation of the standard, and if possible, tailoring your classes to implement such interfaces.

In this article in Portuguese , you can find an example of implementing the pattern using the interfaces of SPL.

    
30.12.2013 / 14:27