Simple class and small thought about how does events work.
<?php
interface IEventType {
public function getType(): ?string;
}
class TestEventType implements IEventType {
private $type = "test";
public function getType(): ?string {
return $this->type;
}
}
class Event {
private $function;
private $eventType;
public function fire(array $args) {
return call_user_func_array($this->function, $args);
}
public function getFunction(): ?callable {
return $this->function();
}
public function setFunction(callable $function): self {
$this->function = $function;
return $this;
}
public function getEventType(): ?IEventType {
return $this->eventType;
}
public function setEventType(IEventType $eventType): self {
$this->eventType = $eventType;
return $this;
}
}
class EventSubscriber {
private $events;
public function addEvent(Event $event): self {
$this->events[] = $event;
return $this;
}
public function removeEvent(Event $event): self {
foreach ($this->events as $eventC) {
if ($eventC === $event) {
unset ($eventC);
}
}
return $this;
}
public function fireEvents(IEventType $eventType): array {
$result = [];
foreach ($this->events as $event) {
if ($event->getEventType() === $eventType) {
$result[] = $event->fire([]);
}
}
return $result;
}
}
$testEventType = new TestEventType();
$event = new Event();
$event->setEventType($testEventType);
$event->setFunction(function () {
echo 55;
return 22;
});
$eventSubscriber = new EventSubscriber();
$eventSubscriber->addEvent($event);
$res = $eventSubscriber->fireEvents($testEventType);
var_dump($res);