Last active
November 28, 2018 08:54
-
-
Save frankdejonge/cb2b6db63f910bf6cbe5263401dd1362 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
interface EventDispatcher | |
{ | |
public function listen(string $event, callable $listener); | |
public function emit(object $event): object; | |
} | |
class ExampleEventDispatcher implements EventDispatcher | |
{ | |
protected $listeners = []; | |
public function listen(string $event, callable $listener) | |
{ | |
$this->listeners[$event][] = $listener; | |
} | |
public function emit(object $event) | |
{ | |
$listeners = $this->listeners[get_class($event)] ?? []; | |
foreach ($listeners as $listener) { | |
$listener($event); | |
} | |
return $event; | |
} | |
} | |
interface CanStopPropagation { | |
public function stopPropagation(); | |
public function hasStoppedPropagation(): bool; | |
} | |
class PropagationAwareEventDispatcher implements EventDispatcher | |
{ | |
protected $listeners = []; | |
public function listen(string $event, callable $listener) | |
{ | |
$this->listeners[$event][] = $listener; | |
} | |
public function emit(object $event) | |
{ | |
$listeners = $this->listeners[get_class($event)] ?? []; | |
$canStopPropagation = $event instanceof CanStopPropagation; | |
foreach ($listeners as $listener) { | |
if ($canStopPropagation && $event->hasStoppedPropagation()) { | |
goto end; | |
} | |
$listener($event); | |
} | |
end: | |
return $event; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$dispatcher = new ExampleEventDispatcher(); | |
class SomethingHappened {} | |
class ListenerOfSomethingHappened { | |
public function __invoke(SomethingHappened $event) | |
{ | |
var_dump($event); | |
} | |
} | |
$dispatcher->listen(SomethingHappened::class, new ListenerOfSomethingHappened()); | |
$dispatcher->emit(new SomethingHappened()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment