1
0

events.trait.php 666 B

12345678910111213141516171819202122232425262728293031
  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. $fn(...$args);
  26. }
  27. }
  28. return $this;
  29. }
  30. }
  31. ?>