FRED™  3.0
FRED™: Framework for Rapid and Easy Development
Event.php
Go to the documentation of this file.
1 <?php
2 
3 namespace Rsi\Fred;
4 
5 /**
6  * Event handler component.
7  */
8 class Event extends Component{
9 
10  protected $_events = [];
11  protected $_counts = [];
12 
13  /**
14  * Start listening to an event.
15  * @param string $name Name of the event (usually with a class name prefix).
16  * @param function $callback Callback function (first parameter must be the sender; others are event specific).
17  * @param int $prio Callbacks with a lower prio value are called before ones with higher values. Otherwise callbacks are
18  * called in the order in which they where added.
19  */
20  public function listen($name,$callback,$prio = 50){
21  \Rsi\Record::add($this->_events,[$name,$prio],[]);
22  $this->_events[$name][$prio][] = $callback;
23  ksort($this->_events[$name]);
24  }
25  /**
26  * Trigger an event.
27  * @param string $name Name of the event (usually with a class name prefix).
28  * @param object $sender,... The initiator of the event, and other parameters for the callback function.
29  * @return mixed Return value if one of the callbacks returned something other than null (this will also directly stop the
30  * chain). Returns null if none of the callbacks functions (if any) returned anything other than null.
31  */
32  public function trigger($name,$sender = null){
33  if($log = $this->component('log')) $log->debug(__CLASS__ . "::trigger('$name',...)",__FILE__,__LINE__);
34  if(array_key_exists($name,$this->_events)){
35  $this->_counts[$name] = $this->count($name) + 1;
36  $params = array_slice(func_get_args(),1);
37  foreach($this->_events[$name] as $events) foreach($events as $callback){
38  if(is_array($callback) && is_string($name = \Rsi\Record::value($callback))) $callback = [$this->component($name),array_pop($callback)];
39  if(($result = call_user_func_array($callback,$params)) !== null) return $result;
40  }
41  }
42  return null;
43  }
44  /**
45  * Number of times an event has been triggered.
46  * @param string $name Name of the event (usually with a class name prefix).
47  * @return int Counter (false if event does not exist).
48  */
49  public function count($name){
50  return $this->_counts[$name] ?? (array_key_exists($name,$this->_events) ? 0 : false);
51  }
52 
53 }
listen($name, $callback, $prio=50)
Start listening to an event.
Definition: Event.php:20
Basic component class.
Definition: Component.php:8
trigger($name, $sender=null)
Trigger an event.
Definition: Event.php:32
count($name)
Number of times an event has been triggered.
Definition: Event.php:49
Event handler component.
Definition: Event.php:8
component($name)
Get a component (local or default).
Definition: Component.php:80