events.trait.php 706 B

123456789101112131415161718192021222324252627282930313233
  1. <?php
  2. trait Events {
  3. private $events = [];
  4. public function on(string $name, Callable $fn){
  5. if(!isset($this->events[$name])){
  6. $this->events[$name] = [];
  7. }
  8. $this->events[$name][] = $fn;
  9. return $this;
  10. }
  11. public function off(string $name, Callable $fn = null){
  12. if(isset($this->events[$name])){
  13. $a = $this->events[$name];
  14. foreach($a as $k => $f){
  15. if(is_null($fn) || $f == $fn){
  16. array_splice($a, $k, 1);
  17. }
  18. }
  19. }
  20. return $this;
  21. }
  22. public function fire(string $name, ...$args){
  23. if(isset($this->events[$name])){
  24. foreach($this->events[$name] as $fn){
  25. if($fn(...$args) === false){
  26. return false;
  27. }
  28. }
  29. }
  30. return true;
  31. }
  32. }
  33. ?>