PHP中的事件驱动架构和钩子

Moa*_*Plz 12 php hook event-driven-design

我正计划开发一个具有PHP后端的游戏来与数据存储库进行通信.我在考虑这个问题,并得出结论,我们的游戏最好的设计范例将是事件驱动的.我希望有一个成就系统(类似于本网站的徽章系统),基本上我希望能够将这些"成就检查"挂钩到游戏中发生的许多不同事件中.即:

当用户执行操作时,将触发钩子Y并调用所有附加函数以检查成就要求.

在构建这样的架构时,我将允许轻松添加新的成就,因为我将要做的就是将检查功能添加到正确的钩子中,其他一切都将落实到位.

我不确定这是否是对我打算做什么的一个很好的解释,但无论如何我正在寻找以下内容:

  1. 有关如何编写事件驱动应用程序代码的良好参考资料
  2. 代码片段展示了如何在PHP中的函数中放置"钩子"
  3. 显示如何将函数附加到第2点中提到的"钩子"的代码片段

关于如何完成2)和3),我有一些想法,但我希望精通这个问题的人可以对最佳实践有所了解.

先感谢您!

hak*_*kre 14

有关如何编写事件驱动应用程序代码的良好参考资料

您可以使用"哑"回调(Demo)执行此操作:

class Hooks
{
    private $hooks;
    public function __construct()
    {
        $this->hooks = array();
    }
    public function add($name, $callback) {
        // callback parameters must be at least syntactically
        // correct when added.
        if (!is_callable($callback, true))
        {
            throw new InvalidArgumentException(sprintf('Invalid callback: %s.', print_r($callback, true)));
        }
        $this->hooks[$name][] = $callback;
    }
    public function getCallbacks($name)
    {
        return isset($this->hooks[$name]) ? $this->hooks[$name] : array();
    }
    public function fire($name)
    {
        foreach($this->getCallbacks($name) as $callback)
        {
            // prevent fatal errors, do your own warning or
            // exception here as you need it.
            if (!is_callable($callback))
                continue;

            call_user_func($callback);
        }
    }
}

$hooks = new Hooks;
$hooks->add('event', function() {echo 'morally disputed.';});
$hooks->add('event', function() {echo 'explicitly called.';});
$hooks->fire('event');
Run Code Online (Sandbox Code Playgroud)

或者实现在事件驱动的应用程序中经常使用的模式:Observer Pattern.

代码片段展示了如何在PHP中的函数中放置"钩子"

上面的手动链接(回调可以存储到变量中)和Observer Pattern的一些PHP代码示例.


bej*_*bee 5

对于PHP,我经常集成Symfony事件组件:http://components.symfony-project.org/event-dispatcher/.

下面是一个简短的示例,您可以在Symfony的" 食谱"部分中找到它.

<?php

class Foo
{
  protected $dispatcher = null;

    // Inject the dispatcher via the constructor
  public function __construct(sfEventDispatcher $dispatcher)
  {
    $this->dispatcher = $dispatcher;
  }

  public function sendEvent($foo, $bar)
  {
    // Send an event
    $event = new sfEvent($this, 'foo.eventName', array('foo' => $foo, 'bar' => $bar));
    $this->dispatcher->notify($event);
  }
}


class Bar
{
  public function addBarMethodToFoo(sfEvent $event)
  {
    // respond to event here.
  }
}


// Somewhere, wire up the Foo event to the Bar listener
$dispatcher->connect('foo.eventName', array($bar, 'addBarMethodToFoo'));

?>
Run Code Online (Sandbox Code Playgroud)

这是我们集成到购物车中的系统,用于创建类似游戏的购物体验,将用户操作挂钩到游戏事件中.当用户执行特定操作时,php触发了导致奖励被触发的事件.

示例1:如果用户单击特定按钮10次,则会收到星号.

示例2:当用户引用朋友并且该朋友注册时,触发事件被奖励原始引用者带点数.