PHP Event Hooking

There comes a time during every programmers career where they need to figure out how to hook on to events.  Today, I will show how to create a simple event register for display.  We’ll start with the ‘display’ class.

Now, make sure to read the comments.  Notice line 38, as that is where the magic happens, but also forces conformity among the classes that register.  Each class that registers needs to have a method called ‘getDisplay’, and the return from each of those functions populates the $myDisplay array.  Now, if you are using a template engine (recommended), you can assign the variable $name to it with the return.  But I’m not going in to creating an actual display class that is fully functional, just demonstrating how to allow anonymous event hooking.  Byanonymous, I mean that the display class isn’t away of anything else within the registered objects, just that they have one function to utilize for display.

Now, that the basic display class is created, we’ll create two classes that will register with it.  Now remember, these are very simple classes that will require a reference to the display class.  In an actual application, the display class will be attached to a ‘site’ class or similar, as will these two additional classes, so they would need a reference to the main site and then link it to the display class from there.

And the main code to tie them together:

Notice how Foo and Bar display since they registered with the display class.  So now, you know how to create a class that allows events to be registered and calls the classes that did register.  This can be useful for so many purposes within a dynamic site, display being only one.

I hope that you found this useful, if you have any questions, feel free to add a comment asking.

No Comments Yet

There are no comments yet. You could be the first!

Leave a Comment

    Search the Blog