How to do a PHP hook system?

后端 未结 3 2227
后悔当初
后悔当初 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:55

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

提交回复
热议问题