How to do a PHP hook system?
You can build an events system as simple or complex as you want it.
/**
* Attach (or remove) multiple callbacks to an event and trigger those callbacks when that event is called.
*
* @param string $event name
* @param mixed $value the optional value to pass to each callback
* @param mixed $callback the method or function to call - FALSE to remove all callbacks for event
*/
function event($event, $value = NULL, $callback = NULL)
{
static $events;
// Adding or removing a callback?
if($callback !== NULL)
{
if($callback)
{
$events[$event][] = $callback;
}
else
{
unset($events[$event]);
}
}
elseif(isset($events[$event])) // Fire a callback
{
foreach($events[$event] as $function)
{
$value = call_user_func($function, $value);
}
return $value;
}
}
Add an event
event('filter_text', NULL, function($text) { return htmlspecialchars($text); });
// add more as needed
event('filter_text', NULL, function($text) { return nl2br($text); });
// OR like this
//event('filter_text', NULL, 'nl2br');
Then call it like this
$text = event('filter_text', $_POST['text']);
Or remove all callbacks for that event like this
event('filter_text', null, false);
Here's another solution:
Creating a hook
Run this wherever you want to create a hook:
x_do_action('header_scripts');
Attach a function to the hook
Then attach a function to the above by doing:
x_add_action('header_scripts','my_function_attach_header_scripts');
function my_function_attach_header_scripts($values) {
/* add my scripts here */
}
Global variable to store all hooks/events
Add this to the top of your main PHP functions file, or equivalent
$x_events = array();
global $x_events;
Base functions
function x_do_action($hook, $value = NULL) {
global $x_events;
if (isset($x_events[$hook])) {
foreach($x_events[$hook] as $function) {
if (function_exists($function)) { call_user_func($function, $value); }
}
}
}
function x_add_action($hook, $func, $val = NULL) {
global $x_events;
$x_events[$hook][] = $func;
}