Simulating Events with PHP 5 - Using the Event-Enabled Class (
Page 4 of 4 )
Using MyEventClass is fairly straightforward. You create an EventHandlerCollection and any event handling methods you want, and you instantiate the class.
$handlers = new EventHandlerCollection();
$handlers->Add(new EventHandler(new Event('OnLoad'),
'handleLoad'));
$handlers->Add(new EventHandler(new Event('OnUnload'),
'handleUnload'));
$obj = new MyEventClass($handlers);
$obj = null;
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.