I am starting a new web application in PHP and this time around I want to create something that people can extend by using a plugin interface. How does one go about writing 'hooks' into their code so that plugins can attach to specific events?
Note that for PHP >= 5.0 you can implement this using the Observer / Subject interfaces defined in the SPL: php.net/manual/en/class.splobserver.php
Pedantic note:this is not an example of the Observer pattern.It's an example of the Mediator Pattern.True observers are purely notification, there is no message passing or conditional notification (nor is there a central manager for controlling notifications).It doesn't make the answer wrong, but it should be noted to stop people calling things by the wrong name...
Note that when using multiple hooks/listeners, you should only return either strings or arrays, not both. I have implemented something similar for Hound CMS - getbutterfly.com/hound.
Isn't this a decorator?
I read up on Wikipedia about this and, whoa, you're right! :)
I'd add DokuWiki to the list of systems you may have a look at. It has a nice event system that allows for a rich plugin ecosystem.
This is more of a "push API" than a "plugin" system - you're providing a way for other services to receive notification of selected events. What is generally meant by "plugins" is that you can install the application and then add functionality to customise its behaviour to your purposes, which requires the plugin to be running locally - or at least have a secure and efficient 2-way communication to provide information to the application not just take it from it. The two features are somewhat distinct, and for many cases a "feed" (e.g. RSS, iCal) is a simple alternative to a push API.