php 事件驅動

<?php
/**
 * 事件驅動模型
 * 簡介:觀察者模式的另外一種形態,觀察者至關於監聽器,被觀察者至關於事件源
 * 目的:事件源產生事件,監聽器監聽事件
 * 總結:事件發生-事件處理模型
 * 組成:監聽器,事件源,事件源管理器
 * User: lionzheng
 * Date: 2018/10/16
 * Time: 15:04
 *
 */

/**
 * 監聽器
 * Class EventListener
 */
class EventListener
{
    protected $name = '';

    public function handleEvent($msg)
    {
        echo "{$this->name} 閱讀了 : $msg \n";
    }
}

/**
 * 事件源 - 事件載體
 * Class EventObject
 */
class EventSource
{
    protected $eventName;
    protected $eventData;

    public function getEventName()
    {
        return $this->eventName;
    }

    public function getEventData()
    {
        return $this->eventData;
    }

}

/**
 * 事件管理器
 * Class EventManager
 */
class EventManager
{
    private static $eventList = [];

    /**
     * 綁定事件
     */
    function attachListener(EventSource $eventObject, EventListener $listener)
    {
        //一個事件名綁定多個監聽器
        self::$eventList[$eventObject->getEventName()][] = $listener;
    }

    /**
     * 解除綁定事件
     */
    public function detach(EventSource $eventObject)
    {
        unset(self::$eventList[$eventObject->getEventName()]);
    }

    /**
     * 觸發事件
     */
    public function fire(EventSource $eventObject)
    {
        foreach (self::$eventList as $attachEventName => $listenerList) {
            //匹配監聽列表
            if ($eventObject->getEventName() == $attachEventName) {
                foreach ($listenerList as $eventListener) {
                    $eventListener->handleEvent($eventObject->getEventData());
                }
            }
        }
    }
}

/**
 * 寫入操做的一個事件監聽器
 * Class WriterListener
 */
class WriterListener extends EventListener
{
    public function __construct($name)
    {
        $this->name = $name;
    }
}

/**
 * 一個寫的事件
 * Class WriteEvent
 */
class Writer extends EventSource
{
    public function __construct($eventName, $eventData)
    {
        $this->eventName = $eventName;
        $this->eventData = $eventData;
        echo "$eventName 發佈了新做 $eventData\n";
        echo "---------------------------------\n";

    }
}

function main()
{
    //初始化管理器
    $eventManager = new EventManager();
    //初始化聽衆
    $listener1 = new WriterListener('lion');
    $listener2 = new WriterListener('2哈');
    $listener3 = new WriterListener('aiwen');
    $listener4 = new WriterListener('yuan');
    //初始化做者
    $writer1 = new Writer('郭敬明', '小時代');
    $writer2 = new Writer('莫言', '人間正道是滄桑');

    $eventManager->attachListener($writer1, $listener1);
    $eventManager->attachListener($writer2, $listener2);
    $eventManager->attachListener($writer2, $listener3);
    $eventManager->attachListener($writer2, $listener4);

    $eventManager->fire($writer1);
    $eventManager->fire($writer2);

}

main();
  

 輸出結果:php

相關文章
相關標籤/搜索