PHP has the drawback of not supporting events. Fortunately, a basic structure can be built to support events in PHP 5. This article tackles that problem with some proof of concept code.
One of the big drawbacks of PHP has always been its lack of events. Events allow programmers to attach new behaviors to objects that are activated when certain conditions are met. Those conditions are announced to the outside world as an event. While all object languages that support events do so a bit differently, some being very simple like JavaScript or VB.NET, others being a real pain in the rear like C#, it should go without saying that the task of creating a framework to simulate events will be much harder.
It seemed reasonable to me that some sort of basic structure could be established to support events in PHP 5, so I set out to whip something up as quickly as possible as a proof of concept. The contents of this article are the work of roughly one programming hour and surely stand to be improved upon, but the basic idea is this: instantiate an object and attach event handlers; the handlers will be executed when the events they are associated with are raised.
This is not an article for beginners, but I would not say you have to be a guru to understand the concepts and the code here. I have tried to keep it as minimal as possible to stay on point.
The Event and EventCollection Classes
First we need to create a simple object to store whatever event information we may need and an object to contain a collection of events. The reason we do not simply store them in an ArrayObject is because we need to be able to quickly check to see whether an event exists in a given collection, which requires code written specifically for the task.
Here is the Event class:
class Event { private $name;
public function GetName() { return $this->name; }
public function __construct($name) { $this->name = $name; } }
As you can see, the class is essentially a container for a string. You could do away with this class in the examples given here, but I chose to go ahead and use an Event class in case at some point we need to store more information about a particular event. The EventCollection class basically wraps an ArrayObject and provides a function to check for an event by name.
class EventCollection { private $events;
public function __construct() { $this->events = new ArrayObject(); }
public function Add($event) { if (!$this->Contains($event)) $this->events->Append($event); }
public function Contains($event) { foreach ($this->events as $e) { if ($e->GetName() == $event) return true; } } }
Again, I chose to use classes for events rather than simply an ArrayObject of strings to provide support for future additions. There is no code in either of these classes that requires explanation, so let us continue.