Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do a PHP hook system?

How do you impliment a hook system in a PHP application to change the code before or after it executes. How would the basic architecture of a hookloader class be for a PHP CMS (or even a simple application). How then could this be extended into a full plugins/modules loader?

(Also, are there any books or tutorials on a CMS hook system?)

like image 791
alecwhardy Avatar asked Dec 01 '11 03:12

alecwhardy


People also ask

How do hooks work in PHP?

PHP or code hook is a specially defined part in the program code that can pass control to an add-on. A hook is declared by calling a special function in the necessary part of code: fn_set_hook('hook_name', $params, [$param2], [$paramN]); Hooking is a very flexible technique; one function can have any number of hooks.

What is a hook system?

A hook is a mechanism by which an application can intercept events, such as messages, mouse actions, and keystrokes. A function that intercepts a particular type of event is known as a hook procedure.

How many types of hooks are there in PHP?

There are two types of hooks: Actions and Filters. To use either, you need to write a custom function known as a Callback , and then register it with a WordPress hook for a specific action or filter.

What is hook WordPress?

WordPress hook is a feature that allows you to manipulate a procedure without modifying the file on WordPress core. A hook can be applied both to action (action hook) and filter (filter hook). Learning about hooks is essential for any WordPress user.


1 Answers

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);
like image 179
Xeoncross Avatar answered Oct 02 '22 17:10

Xeoncross