资讯专栏INFORMATION COLUMN

Symfony EventDispatcher 组件的使用与解读

ixlei / 2658人阅读

摘要:事件代码事件名,事件的唯一标识在监听器里要操作的对象在监听器里要操作的对象继承在订阅器的业务逻辑上,需要使用和对象,所以本事件包含这两个类的对象。

大家好,这篇文章将通过我在实际开发工作中的例子,来介绍Symfony的EventDispatcher组件的使用及实现原理。

这个组件在实际开发过程中非常的有用,它能够使代码的业务逻辑变的非常清晰,增加代码的复用性,代码的耦合性也大大降低。

简介

具体的介绍大家可以查看官方的文档,下面是文档地址。

文档地址

组成

一个 dispatcher 对象,保存了事件名称和其对应监听器

一个 event,有一个全局唯一的事件名称。包含一些在订阅器里需要访问的对象。

使用示例
1. 初始化,添加相应监听事件
# 初始时,添加监听器
$dispatcher = new EventDispatcher();

$disptacher->addSubscriber(new BIReportSubscriber());   // BI上报功能
$disptacher->addSubscriber(new MediaPlayerSubscriber());  // 维护播放器信息统一

SymfonyComponentEventDispatcherEventDispatcher

2. 监听的事件
class BIReportSubscriber implements EventSubscriberInterface
{
    public static function getSubscribedEvents ()
    {
        // 监听的不同事件,当事件触发时,会调用 onResponse 方法
        return [
            MusicResponseEvent::NAME => "onResponse",  
            ChildrenResponseEvent::NAME => "onResponse",
            FmResponseEvent::NAME => "onResponse",
            NewsResponseEvent::NAME => "onResponse",
        ];
    }
    
    public function onResponse(AResponseEvent $event)
    {
        /*
         * 一些具体的业务逻辑
         * 进行 BI 上报
         */
    }
class MediaPlayerSubscriber implements EventSubscriberInterface
{
    public static function getSubscribedEvents ()
    {
        return [
            MusicResponseEvent::NAME => "onResponse",
            FmResponseEvent::NAME => "onResponse",
            ChildrenResponseEvent::NAME => "onResponse",
            NewsResponseEvent::NAME => "onResponse",
        ];
    }
    public function onResponse(AResponseEvent $event)
    {
        /*
         * 一些具体的业务逻辑
         * 维护播放器信息统一
         */
    }

实现 getSubscribedEvents 方法,完成事件的绑定。当事件触发时,dispatcher 会调用绑定的方法,并将抛出的事件当做参数传入。

事件绑定的方法 onResponse 可以是任何名字。

onResponse 方法中,通过 $event 获取要操作的对象。

3. 事件代码
class FmResponseEvent extends Event
{
    const NAME = "fm.response";  // 事件名,事件的唯一标识

    protected $request;  // 在监听器里要操作的对象

    protected $response;  // 在监听器里要操作的对象

    public function __construct (Request $request, Response $response)
    {
        $this->request = $request;
        $this->response = $response;
    }

    /**
     * @return Request
     */
    public function getRequest()
    {
        return $this->request;
    }

    /**
     * @return Response
     */
    public function getResponse()
    {
        return $this->response;
    }
}

继承 SymfonyComponentEventDispatcherEvent

在订阅器的业务逻辑上,需要使用 $request 和 $response 对象,所以本事件包含这两个类的对象。

4. 触发事件
 $event = new FmResponseEvent($request, $response);
 $dispatcher->dispatch($event::NAME, $event);

dispathcer 会按照优先级,依次执行订阅器中事件绑定的方法

原码解读
1 简化的 EventDispatcher 源码
class EventDispatcher implements EventDispatcherInterface
{
    private $listeners = array();
    
    private $sorted = array();
    
    /**
     * 触发事件
     */
    public function dispatch($eventName, Event $event)
    {
        if ($listeners = $this->getListeners($eventName)) {
            $this->doDispatch($listeners, $eventName, $event);
        }

        return $event;
    }

    /**
     *  根据事件名,搜索监听器
     */
    public function getListeners($eventName)
    {
        if (empty($this->listeners[$eventName])) {
            return array();
        }

        if (!isset($this->sorted[$eventName])) {
           $this->sortListeners($eventName);
        }

        return $this->sorted[$eventName];
    }
    
    /**
     * 换优先级将监听器排序
     * @param string $eventName
     */
    private function sortListeners($eventName)
    {
        krsort($this->listeners[$eventName]);
        $this->sorted[$eventName] = array();

        foreach ($this->listeners[$eventName] as $priority => $listeners) {
            foreach ($listeners as $k => $listener) {
                if (is_array($listener) && isset($listener[0]) && $listener[0] instanceof Closure) {
                    $listener[0] = $listener[0]();
                    $this->listeners[$eventName][$priority][$k] = $listener;
                }
                $this->sorted[$eventName][] = $listener;
            }
        }
    }


    protected function doDispatch($listeners, $eventName, Event $event)
    {
        foreach ($listeners as $listener) {
            if ($event->isPropagationStopped()) {
                break;
            }
            call_user_func($listener, $event, $eventName, $this);
     }
    
    /**
     * 添加订阅器
     */
    public function addSubscriber(EventSubscriberInterface $subscriber)
    {
        foreach ($subscriber->getSubscribedEvents() as $eventName => $params) {
            if (is_string($params)) {
                $this->addListener($eventName, array($subscriber, $params));
            } elseif (is_string($params[0])) {
                $this->addListener($eventName, array($subscriber, $params[0]), isset($params[1]) ? $params[1] : 0);
            } else {
                foreach ($params as $listener) {
                    $this->addListener($eventName, array($subscriber, $listener[0]), isset($listener[1]) ? $listener[1] : 0);
                }
            }
        }
    }
    
    public function addListener($eventName, $listener, $priority = 0)
    {
        $this->listeners[$eventName][$priority][] = $listener;
        unset($this->sorted[$eventName]);
    }
}

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/29914.html

相关文章

  • tastphp,为现代化 phper 准备 PHP 框架

    摘要:大家好,推荐下我们团队自己研发的框架为现代化的准备的。可拔插,扩展性强。借鉴了等优秀框架。有兴趣的可以关注下。最渴望有人给我们提交。中文文档基础已经写完,剩下努力写中。。。 大家好,推荐下我们团队自己研发的框架:tastphp 为现代化的phper准备的。可拔插,扩展性强。借鉴了Symfony、Laravel、Silex等优秀框架。 有兴趣的可以关注下 tastphp。最渴望有人给...

    meteor199 评论0 收藏0
  • Laravel核心解读 -- Request

    摘要:根据提供的超级全局数组来创建实例上面的代码有一处需要额外解释一下,自开始内建的可以通过命令行解释器来启动,例如但是内建有一个是将和这两个请求首部存储到了和中,为了统一内建服务器和真正的中的请求首部字段所以在这里做了特殊处理。 Request 很多框架都会将来自客户端的请求抽象成类方便应用程序使用,在Laravel中也不例外。IlluminateHttpRequest类在Laravel框...

    K_B_Z 评论0 收藏0
  • Swoft| Swoft 框架组件化改造

    摘要:框架组件化改造框架从单体应用到组件化改造的架构升级之路经过一年多的开发框架功能越来越完善也越来越复杂初创时期的单体应用已经无法支撑项目的快速发展于是开发组在年前为版制定了组件化改造的重构方案内容速览组件化原理包管理基础知识组件化方案来 date: 2018-3-21 13:22:16title: Swoft| Swoft 框架组件化改造description: Swoft 框架从单体应...

    desdik 评论0 收藏0
  • SymfonyConsole组件简单使用

    摘要:本文目的是多的组件进行简单的使用。方法中设置了命令的名称,即命令中的最后一个单词方法中定义了该命令的执行过程,即输出再看看入口文件这里的方法将我们定义的添加到了命令行中。 Symfony的Console组件的简单使用。 本文目的是多Symfony的Console组件进行简单的使用。达到这样的效果: 输入 php console test 输出 hello console. ...

    instein 评论0 收藏0
  • 原生js,编写一个自定义事件监听

    摘要:前几天一哥们,去面试遇到到一个用原生编写的事件监听,原题是这样子滴分割线然后就兴致勃勃的去看一下,大神的可以直接忽略,就希望帮到一小部分的人就很开心啦简单原理就是往里面的挂载一个函数,然后在里面调用这个函数,这么一说是不是觉得很简单好直接上 前几天一哥们,去面试遇到到一个用原生js 编写的事件监听, 原题是这样子滴! function EventDispatcher() { } /...

    mylxsw 评论0 收藏0

发表评论

0条评论

ixlei

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<