event.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. <?php namespace Laravel;
  2. class Event {
  3. /**
  4. * All of the registered events.
  5. *
  6. * @var array
  7. */
  8. public static $events = array();
  9. /**
  10. * Determine if an event has any registered listeners.
  11. *
  12. * @param string $event
  13. * @return bool
  14. */
  15. public static function listeners($event)
  16. {
  17. return isset(static::$events[$event]);
  18. }
  19. /**
  20. * Register a callback for a given event.
  21. *
  22. * <code>
  23. * // Register a callback for the "start" event
  24. * Event::listen('start', function() {return 'Started!';});
  25. *
  26. * // Register an object instance callback for the given event
  27. * Event::listen('event', array($object, 'method'));
  28. * </code>
  29. *
  30. * @param string $event
  31. * @param mixed $callback
  32. * @return void
  33. */
  34. public static function listen($event, $callback)
  35. {
  36. static::$events[$event][] = $callback;
  37. }
  38. /**
  39. * Fire an event and return the first response.
  40. *
  41. * <code>
  42. * // Fire the "start" event
  43. * $response = Event::first('start');
  44. *
  45. * // Fire the "start" event passing an array of parameters
  46. * $response = Event::first('start', array('Laravel', 'Framework'));
  47. * </code>
  48. *
  49. * @param string $event
  50. * @param array $parameters
  51. * @return mixed
  52. */
  53. public static function first($event, $parameters = array())
  54. {
  55. return head(static::fire($event, $parameters));
  56. }
  57. /**
  58. * Fire an event so that all listeners are called.
  59. *
  60. * <code>
  61. * // Fire the "start" event
  62. * $responses = Event::fire('start');
  63. *
  64. * // Fire the "start" event passing an array of parameters
  65. * $responses = Event::fire('start', array('Laravel', 'Framework'));
  66. * </code>
  67. *
  68. * @param string $event
  69. * @param array $parameters
  70. * @return array
  71. */
  72. public static function fire($event, $parameters = array())
  73. {
  74. $responses = array();
  75. if (static::listeners($event))
  76. {
  77. foreach (static::$events[$event] as $callback)
  78. {
  79. $responses[] = call_user_func_array($callback, $parameters);
  80. }
  81. }
  82. return $responses;
  83. }
  84. }