Consider an app that allows plugins to react to its program flow.
I know 2 ways to achieve this: hooks and events
1. Hooks
Use calls to empty functions inside the main program flow. These functions can be overriden by plugins.
For example, Drupal CMS implements hooks which are available to modules and themes. Here's an example of how hook is implemented in a file_copy function.
function file_copy(stdClass $source, $destination = NULL, $replace = FILE_EXISTS_RENAME) {
// ... [File copying routine]
// Inform modules that the file has been copied.
module_invoke_all('file_copy', $file, $source);
return $file;
// ...
}
A module can implement a modulename_file_copy($file, $source)
function which will be called by the module_invoke_all
in file_copy
. After this function finishes, the file_copy
will resume execution.
2. Events
Have the app dispatch events, which can be listened to by the plugins. After receiving an event that it's been subscribed to, a plugin will intercept the program flow and perform neccessary operations.
For example, a jQuery gallery plugin Fotorama implements several events. As an example, here's a part of its show
method that fires the fotorama:show
event.
that.show = function (options) {
// ... [show the new frame]
// [fire the event]
options.reset || triggerEvent('show', {
user: options.user,
time: time
});
// ... [do lots of other stuff with navigation bars, etc.]
};
A script can listen to this event and do something when it fires:
$('.fotorama').on(
'fotorama:show',
function (e, fotorama, extra) {
console.log(e.type + (extra.user ? ' after user’s touch' : ''));
console.log('transition duration: ' + extra.time);
}
);
QUESTION
Are there other mainstream ways to implement such plugin behaviour?
If not, when should one use hooks, and when should one use events? Considering the ultimate goal is to make the code more maintanable and readable, from both the app and the plugin developer's perspective?