How to do a PHP hook system?

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

    this solutions has some problems that you can't set several function for one callable hook. you can fallow this code.

    
    
     $action = [];
    
     function apply($hook, $args){
        global $action;
        $action[$hook]['args'] = $args;
        return doa($hook, $args);
     }
    
     function add($hook, $func){
        global $action;
        $action[$hook]['funcs'][] = $func;
     }
    
     function doa($hook,$args){
        global $action;
        if(isset($action[$hook]['funcs'])){
            foreach($action[$hook]['funcs'] as $k => $func){
                call_user_func_array($func, $args);
           }
        }
        
     }
    
     add('this_is', 'addOne');
    function addOne($user){
        echo "this is test add one $user 
    "; } add('this_is', function(){ echo 'this is test add two
    '; }); add('this_is_2', 'addTwo'); function addTwo($user, $name){ echo $user . ' ' . $name . '
    '; } function test(){ echo 'hello one
    '; apply('this_is', ['user'=> 123]); } function test2(){ echo 'hello two
    '; apply('this_is_2', ['user'=> 123, 'name' => 'mohammad']); } test(); test2();

提交回复
热议问题