1
0

events.trait.php 632 B

1234567891011121314151617181920212223242526272829
  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. }
  21. public function fire(string $name, ...$args){
  22. if(isset($this->events[$name])){
  23. foreach($this->events[$name] as $fn){
  24. $fn(...$args);
  25. }
  26. }
  27. }
  28. }
  29. ?>