1
0

events.trait.php 723 B

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