代码之家  ›  专栏  ›  技术社区  ›  Atif

没有面向对象的观察者模式逻辑?

  •  2
  • Atif  · 技术社区  · 16 年前

    我在考虑在我的网站上实现一个类似于观察者模式的逻辑来实现钩子。

    我要找的是类似的东西 Best way to allow plugins for a PHP application

    但是那里的代码太有限了,因为我不能将多个钩子附加到同一个侦听器。

    谢谢您

    3 回复  |  直到 9 年前
        1
  •  3
  •   berkes    16 年前

    如果您喜欢通过示例学习,您可以查看CMS Drupal,它不是OOP,而是使用observer模式,称为 hooks 所有的地方都允许模块化设计。

    吊钩的工作原理如下:

    • 如果存在,调用它并使用它的输出(或者不使用它)

    例如:

    这种神奇发生在所谓的user\u回调中。 An example

    $hook = 'insert'
    foreach (module_implements($hook) as $module) {
      $function = $module .'_'. $hook;
      $result = call_user_func_array($function, $args);
    }
    

    module_implements 可能看起来像:

    $list = module_list(FALSE, TRUE, $sort); //looks for files that are considered "modules" or "addons".
    foreach ($list as $module) {
      if (function_exists($module.'_'.$hook)) { //see if the module has the hook 'registered'
        $implementations[$hook][] = $module; //if so: add it to a list with functions to be called.
      }
    }
    
        2
  •  1
  •   ircmaxell    16 年前

    hook() 函数调用命名事件和“*”事件中的所有“hook”。

    然后,简单地做:

    add_listener('*', 'mycallback');
    
        3
  •  0
  •   Artefacto    16 年前

    看一看 Spl_Observer .

    推荐文章