hook.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. <?php
  2. /**
  3. * This class manages the hooks. It basically provides two functions: adding
  4. * slots and emitting signals.
  5. */
  6. class OC_Hook{
  7. static private $registered = array();
  8. /**
  9. * @brief connects a function to a hook
  10. * @param string $signalclass class name of emitter
  11. * @param string $signalname name of signal
  12. * @param string $slotclass class name of slot
  13. * @param string $slotname name of slot
  14. * @return bool
  15. *
  16. * This function makes it very easy to connect to use hooks.
  17. *
  18. * TODO: write example
  19. */
  20. static public function connect( $signalclass, $signalname, $slotclass, $slotname ) {
  21. // Create the data structure
  22. if( !array_key_exists( $signalclass, self::$registered )) {
  23. self::$registered[$signalclass] = array();
  24. }
  25. if( !array_key_exists( $signalname, self::$registered[$signalclass] )) {
  26. self::$registered[$signalclass][$signalname] = array();
  27. }
  28. // register hook
  29. self::$registered[$signalclass][$signalname][] = array(
  30. "class" => $slotclass,
  31. "name" => $slotname );
  32. // No chance for failure ;-)
  33. return true;
  34. }
  35. /**
  36. * @brief emits a signal
  37. * @param string $signalclass class name of emitter
  38. * @param string $signalname name of signal
  39. * @param array $params defautl: array() array with additional data
  40. * @return bool, true if slots exists or false if not
  41. *
  42. * Emits a signal. To get data from the slot use references!
  43. *
  44. * TODO: write example
  45. */
  46. static public function emit( $signalclass, $signalname, $params = array()) {
  47. // Return false if there are no slots
  48. if( !array_key_exists( $signalclass, self::$registered )) {
  49. return false;
  50. }
  51. if( !array_key_exists( $signalname, self::$registered[$signalclass] )) {
  52. return false;
  53. }
  54. // Call all slots
  55. foreach( self::$registered[$signalclass][$signalname] as $i ) {
  56. try {
  57. call_user_func( array( $i["class"], $i["name"] ), $params );
  58. } catch (Exception $e){
  59. OC_Log::write('hook', 'error while running hook (' . $i["class"] . '::' . $i["name"] . '): '.$e->getMessage(), OC_Log::ERROR);
  60. }
  61. }
  62. // return true
  63. return true;
  64. }
  65. /**
  66. * clear hooks
  67. * @param string $signalclass
  68. * @param string $signalname
  69. */
  70. static public function clear($signalclass='', $signalname='') {
  71. if($signalclass) {
  72. if($signalname) {
  73. self::$registered[$signalclass][$signalname]=array();
  74. }else{
  75. self::$registered[$signalclass]=array();
  76. }
  77. }else{
  78. self::$registered=array();
  79. }
  80. }
  81. }