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.
Using MyEventClass is fairly straightforward. You create an EventHandlerCollection and any event handling methods you want, and you instantiate the class.
function handleLoad($sender, $args) { print 'object '.get_class($sender).' loaded with '.count ($args).' args!<br />'; }
function handleUnload($sender, $args) { print 'object '.get_class($sender).' unloaded with '.count ($args).' args!'; }
If you create a PHP page with all the code in it from this article and run it, you will see the following on your screen:
object MyEventClass loaded with 1 args! object MyEventClass unloaded with 1 args!
Obviously this is a rather minimalistic (and pointless) implementation, but it does demonstrate the usage of the event handlers and the event-enabled class. Pretty cool, yes?
Conclusion
Hopefully this article has piqued your interest and you will experiment, improve my code, and create a fantastic open source event framework for PHP, which I am far, far too lazy to do myself. There are some obvious points where refactoring is called for, such as creating an interface or an abstract base class that event-enabled classes adhere to, or providing a more effective design of the event and handler classes. I intend to use the code I’ve created here in my next PHP project, and I hope you will, too. Be sure to let me know how it works out and post any nifty improvements in the dicussion thread of the article.