Created
August 13, 2020 10:02
-
-
Save kobus1998/ba35703efe68f266fc65e0042fb8a4ee to your computer and use it in GitHub Desktop.
event listener with priorities
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 | |
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