How to do a PHP hook system?

后端 未结 3 2229
后悔当初
后悔当初 2020-12-12 21:30

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

3条回答
  •  无人及你
    2020-12-12 21:57

    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);
    

提交回复
热议问题