Skip to content

Instantly share code, notes, and snippets.

@kobus1998
Created March 21, 2018 15:52
Show Gist options
  • Save kobus1998/9e1cafb784120adf03b1bca0a14d6732 to your computer and use it in GitHub Desktop.
Save kobus1998/9e1cafb784120adf03b1bca0a14d6732 to your computer and use it in GitHub Desktop.
Event dispatcher
<?php
class Event
{
public static $events;
public function __construct()
{
self::$events = [];
}
public static function listen($name, $callback, $prio = 0)
{
self::$events[$name][$prio][] = $callback;
}
public static function sort($name = null)
{
$sorts;
if ($name !== null)
{
$sorts = self::$events[$name];
krsort($sorts);
}
else
{
foreach (self::$events as $events)
{
arsort($events);
$sorts[] = $events;
}
}
return $sorts;
}
public function dispatch($name = null)
{
$events = self::sort($name);
foreach ($events as $key => $value)
{
foreach ($value as $callback)
{
$callback();
}
}
}
}
Event::listen('name', function () {
echo 1 . "\n";
}, 1);
Event::listen('name', function () {
echo 2 . "\n";
}, 0);
Event::listen('name', function () {
echo 3 . "\n";
}, 3);
Event::dispatch('name');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment