钩子系统的变量参数支持


Variable argument support for hook system

我正在为php应用程序创建一个操作挂钩系统。以下是我迄今为止所做的工作。$where是钩子的名称当一个挂钩位置有多个操作时,$priority决定所遵循的顺序。(当到达挂钩位置并且我的应用程序核心运行任何挂钩操作时,会调用hook::execute()

class hooks{
    private $hookes;    
    function __construct()
    {
        $hookes=array();        
    }
    function add_action($where,$callback,$priority=50)
    {
        if(!isset($this->hookes[$where]))
            $this->hookes[$where]=array();
        $this->hookes[$where][$callback]=$priority;
    }
    function remove_action($where,$callback)
    {
        if(isset($this->hookes[$where][$callback]))
            unset($this->hookes[$where][$callback]);
    }
    static function compare($a,$b)
    {
        return $a>$b?1:-1;
    }
    function execute($where)
    {
        if(isset($this->hookes[$where])&&is_array($this->hookes[$where]))
        {
            usort($this->hookes[$where],"hook::compare");
            foreach($this->hookes[$where] as $callback=>$priority)
            {
                call_user_func($callback);
            }
        }
    }
};

我的问题是在execute($where)中如何让它接受变量参数列表并在call_user_func($callback);中传递它们对于要执行的不同调用,回调中可能会传递数量可变的参数。

您可以使用call_user_func_array函数,第二个参数是带参数的数组

试试这个,

  Change add_action($where,$callback,$priority=50) 

  add_action($where,Callable $callback,$priority=50) (PHP 5.4) 
  add_action($where,$callback,$priority=50) ( ALL )

更改

foreach($this->hookes[$where] as $callback=>$priority)
{
    call_user_func($callback);
}

foreach($this->hookes[$where] as $callback=>$priority)
{
    if(is_callable($callback))
    {
        $callback();
    }
    //call_user_func($callback);
}

样本代码

$hooks = new hooks();
$hooks->add_action("WHERE",function()
{
    //Callback Code 
},5);