2012-03-17 48 views
1

我正在为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); 对于不同的要执行的调用,可能会在回调中传递可变数量的参数。

回答

3

可以使用call_user_func_array功能,第二个参数是数组参数

+0

所以如果我通过'阵列( “数据到过滤器”,一些-其他数据,3)'在call_user_func,它将调用功能回调为'function_name(“data-to-filter”,some-other-data,3);'或'function_name(array(“data-to-filter”,some-other-data,3)); – 2012-03-17 08:25:39

+1

function_name(“data-to-filter”,some-other-data,3) – Slawek 2012-03-17 08:27:38

1

试试这个,

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

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

CHANGE

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

谢谢。第一个答案让我的代码工作。 – 2012-03-17 10:24:24

+0

不用客气..当你开始拥有大量的代码时,这只是更清晰和更容易阅读......:D – Baba 2012-03-18 14:51:24