如何将两种方法合二为一


How to Combine Two Methods Into One

我正在做一个插件类,它既包括事件,也包括MVC PHP应用程序的钩子。

事件被设计为在状态变化时调用,正如想象的那样,主要是在模型中调用,因为这是数据变化的地方,也有一些分散到控制器中,用于登录,注销等。

我希望钩子在大多数情况下对整个应用程序的方法可用,会有一些例外。

我已经建立了钩子的存储和注册,然后它们被推送到我的注册表类,所以它们在应用程序范围内可用。

钩子的存储方式如下:

Array
 (
  [admin_controller] => Array // type of hook
   (
     [0] => Array
      (
        [class] => 'Admin'Controller'Tool'Test // class to hook
        [method] => index // method to hook
        [callback] => /Plugin/Test/Hooks/Controller/exampleHook // callback to run
        [arguments] => Array  // any arguments required
          (
            [heading_title] => Example Test Page
            [item_title] => Item title
           )
       )
    )
)

但是现在我不确定如何将这两种方法合二为一。我不想让钩子覆盖原来的方法,只是添加到它。

我也不想在1700文件应用程序的每个方法中监听它:p

是否有一种方法可以获得给定方法的内容,并将其传递给匿名函数以将两者构建为一体,或者我应该反映它?

要做到这一点,最好的技术是什么?

对于任何感兴趣的人,我使用闭包将回调作为参数传递给现有方法。

$callable = false;
$hook_key = str_replace('''', '', strtolower($prefix)) . '_controller';
if (array_key_exists($hook_key, $hooks)):
    foreach($hooks[$hook_key] as $hook):
        if ($hook['class'] === $class && $hook['method'] === $this->method):
            $mthd = basename($hook['callback']);
            $cls  = rtrim(str_replace($mthd, '', $hook['callback']), '/');
            $callback = array(
                'class'  => str_replace('/', '''', $cls),
                'method' => $mthd,
                'args'   => $hook['arguments']
            );
            $callable = function () use ($callback) {
                $hook = new $callback['class'];
                if (is_callable(array($hook, $callback['method']))):
                    return call_user_func_array(array($hook, $callback['method']), $callback['args']);
                endif;
            };
        endif;
        if ($callable):
            $this->args[] = $callable();
        endif;
    endforeach;
endif;

唯一剩下的问题是钩子参数数组在执行时丢失了它的键。

当将func_get_args()转储到上面的回调时,它会产生:

array (size=2)
  0 => string 'Example Test Page' (length=17)
  1 => string 'Item title' (length=10)

如果我将'args' => $hook['arguments']包装在数组'args' => array($hook['arguments'])中,则键保留,但数组嵌套。

array (size=1)
  0 => 
    array (size=2)
      'heading_title' => string 'Example Test Page' (length=17)
      'item_title' => string 'Item title' (length=10)