hook.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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 $signalclass class name of emitter
  11. * @param $signalname name of signal
  12. * @param $slotclass class name of slot
  13. * @param $slotname name of slot
  14. * @returns true/false
  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 emitts a signal
  37. * @param $signalclass class name of emitter
  38. * @param $signalname name of signal
  39. * @param $params defautl: array() array with additional data
  40. * @returns 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. }