EventDispatcher

Данный компонент, предназначен для взаимодействия компонентов между друг другом не напрямую, а через посредника EventDispatcher
Представлю очень грубый пример реализации:

class Event {
    public $name;
    public function getEvent(){
        return $this->event;
    }
}

class SomeSubscribe {
    public function process($object){
        $object->property = 'MODIFIED';
        return $object;
    }
}


class SecondSomeSubscribe {
    public function process($object){
        $object->property = 'MODIFIED 2';
        return $object;
    }
}

class SomeEvent extends Event {
    const NAME = 'testEvent';
    public $event;
    public function __construct($event, $name){
        $this->event = $event;
        $this->name = $name;
    }
}

class EventDispatcher {
    private $events;
    private $subscribers;
    public function addEvent(Event $event){
        $this->events[$event->name] = $event;
    }
    public function addSubscribe($eventName, $objectSubscrube){
        $this->subscribers[$eventName] = $objectSubscrube;
    }
    public function dispatch($name, $event=null){
        $result = null;
        if(null === $event){
            foreach($this->subscribers as $subscribe){
                $result = $subscribe->process($this->events[$name]->getEvent());
            }
        } else {
            foreach($this->subscribers as $subscribe){
                $result = $subscribe->process($event->getEvent());
            }
        }
        return $result;
    }
}


class ObjectEvent {
    public $property;
    public function getPropertyEvent(){
        return $this->property;    
    }
}

$testEvent = new ObjectEvent();
$testEvent->property = 'SOMEPROPERTY_SET_ONCE';

$dispatcher = new EventDispatcher();
$dispatcher->addSubscribe(SomeEvent::NAME, new SomeSubscribe());
$dispatcher->addSubscribe(SomeEvent::NAME, new SecondSomeSubscribe());
$dispatcher->addEvent(new SomeEvent($testEvent, SomeEvent::NAME));
$modifyObjectEvent = $dispatcher->dispatch(SomeEvent::NAME);
var_dump($modifyObjectEvent);

Рефачить и рефачить

Loading

EventDispatcher: 6 комментариев

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *