Skip to content

Instantly share code, notes, and snippets.

@kobus1998
Created August 13, 2020 10:02
Show Gist options
  • Save kobus1998/ba35703efe68f266fc65e0042fb8a4ee to your computer and use it in GitHub Desktop.
Save kobus1998/ba35703efe68f266fc65e0042fb8a4ee to your computer and use it in GitHub Desktop.
event listener with priorities
<?php
class Event
{
public $priority;
public $call;
public $name;
public function __construct(string $name, callable $call, int $priority = 0)
{
$this->name = $name;
$this->call = $call;
$this->priority = $priority;
}
public function execute($var)
{
$call = $this->call;
if (is_callable($call)) {
return $call($var);
}
}
}
class Listener
{
protected $events = [];
public function register(Event $event)
{
$this->events[] = $event;
return $this;
}
/**
* @return Event[]
*/
public function getEvents()
{
$events = $this->events;
usort($events, function ($a, $b) {
return $a < $b;
});
return $events;
}
public function run($var)
{
foreach($this->getEvents() as $event)
{
$event->execute($var);
}
}
}
$ev1 = new Event('a', function () {echo 'a';}, 2);
$ev2 = new Event('b', function () {echo 'b';}, 3);
$ev3 = new Event('3', function () {echo 'c';}, 1);
$l = new Listener();
$l->register($ev1);
$l->register($ev2);
$l->register($ev3);
$l->run(1);
// bac
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment