Skip to content

Instantly share code, notes, and snippets.

@gitawego
Last active February 20, 2020 11:29
Show Gist options
  • Save gitawego/3656310 to your computer and use it in GitHub Desktop.
Save gitawego/3656310 to your computer and use it in GitHub Desktop.
Event(NodeJs style) class for PHP
/**
* Created by IntelliJ IDEA.
* User: hongbo
* Date: 4/26/12
* Time: 9:59 AM
*/
class Event
{
protected $events = array();
public function emit($event, $args = array())
{
if(isset($this->events[$event]))
{
foreach($this->events[$event] as $func)
{
call_user_func($func, $args);
}
}
}
public function on($event, Closure $func)
{
if(!isset($this->events[$event])){
$this->events[$event] = array();
}
$this->events[$event][] = $func;
$idx = array_push($this->events[$event],$func) -1;
$self = $this;
return function() use($idx,$event,&$self){
array_splice($self->events[$event],$idx,1);
return $self;
};
}
public function once($event,Closure $func){
if(!isset($this->events[$event])){
$this->events[$event] = array();
}
$idx = count($this->events[$event]);
$self = $this;
$_func = function($args) use(&$func,$idx,$event,&$self){
call_user_func($func, $args);
array_splice($self->events[$event],$idx,1);
};
array_push($self->events[$event],$_func);
}
public function off($event, Closure $func)
{
if(!isset($this->events[$event])){
return;
}
$this->events[$event] = array_filter($this->events[$event],function($item) use ($func){
return $item == $func;
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment