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

问题描述 投票:0回答:4

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

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

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

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

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

关于如何实现 2) 和 3),我有一些想法,但我希望精通该问题的人能够阐明最佳实践。

提前谢谢您!

php hook event-driven-design
4个回答
16
投票

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

您可以使用“哑”回调演示)来做到这一点:

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');

或者实现事件驱动应用程序中常用的模式:观察者模式

显示如何在 PHP 函数中放置“钩子”的代码片段

上面的手动链接(回调可以存储到变量中)和一些观察者模式的 PHP 代码示例


5
投票

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

下面是一个简短的示例,您可以在 Symfony 的 Recipe 部分中找到它的扩展。

<?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'));

?>

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

示例 1:如果用户点击特定按钮 10 次,他们就会收到一颗星。

示例 2:当用户推荐朋友并且该朋友注册时,会触发一个活动,奖励原始推荐人积分。


1
投票

查看 CodeIgniter,因为它有 内置挂钩

只需启用钩子:

$config['enable_hooks'] = TRUE;

然后定义你的钩子:

 $hook['post_controller_constructor'] = array(
                                'class'    => 'Hooks',
                                'function' => 'session_check',
                                'filename' => 'hooks.php',
                                'filepath' => 'hooks',
                                'params'   => array()
                                ); 

然后在你的课堂上使用它:

<?php

    class Hooks {
        var $CI;

        function Hooks() {
            $this->CI =& get_instance();
        }

        function session_check() {
            if(!$this->CI->session->userdata("logged_in") && $this->CI->uri->uri_string != "/user/login")
                redirect('user/login', 'location');
        }
    }

?> 

0
投票

新访问者可能会通过研究 ReactPHP 来深入了解 O/P 询问的答案。如果您今天(2023 年)搜索“PHP 中的事件驱动架构”这一短语,ReactPHP 似乎是共同点。

© www.soinside.com 2019 - 2024. All rights reserved.