hook.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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. call_user_func( array( $i["class"], $i["name"] ), $params );
  57. }
  58. // return true
  59. return true;
  60. }
  61. /**
  62. * clear hooks
  63. * @param string $signalclass
  64. * @param string $signalname
  65. */
  66. static public function clear($signalclass='', $signalname='') {
  67. if($signalclass) {
  68. if($signalname) {
  69. self::$registered[$signalclass][$signalname]=array();
  70. }else{
  71. self::$registered[$signalclass]=array();
  72. }
  73. }else{
  74. self::$registered=array();
  75. }
  76. }
  77. }