router.class.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. <?php
  2. require_once('path.class.php');
  3. require_once('response.class.php');
  4. class Router {
  5. private $_paths = array();
  6. private $_base = '/';
  7. private $responses = array();
  8. public function __construct($base = null, $paths = null){
  9. if($paths != null){
  10. $this->paths($paths);
  11. }
  12. if($base != null){
  13. $this->base($base);
  14. }
  15. }
  16. public function __get($name){
  17. switch($name){
  18. case 'base':
  19. return $this->_base;
  20. break;
  21. }
  22. }
  23. public function __clone(){
  24. // No cloning
  25. }
  26. public function __destruct(){
  27. $this->_paths = array();
  28. }
  29. public function __toString(){
  30. return "[Router]";
  31. }
  32. public function base($base){
  33. $this->_base = $base;
  34. }
  35. public function url($url){
  36. return preg_replace('/(\/+)/','/',$url);
  37. }
  38. // fn = function(response,args){}
  39. public function path($path,$fn){
  40. $obj = false;
  41. foreach($this->_paths as $k => $p){
  42. if($p->path == $path){
  43. $obj = $p;
  44. }
  45. }
  46. if(!$obj){
  47. $obj = new Path($path);
  48. array_push($this->_paths,$obj);
  49. }
  50. return $obj->handle($fn);
  51. }
  52. public function paths($paths){
  53. foreach($paths as $path => $fn){
  54. $this->path($path,$fn);
  55. }
  56. }
  57. public function clear(){
  58. $this->_paths = array();
  59. }
  60. public function handle($url,$res = null,$fn = null,$onerror = null){
  61. if($url[0] != '/'){
  62. $url = '/'.$url;
  63. }
  64. if(is_null($res)){
  65. $res = new Response($url);
  66. }else{
  67. $res->url = $url;
  68. }
  69. if(!in_array($res,$this->responses)){
  70. array_push($this->responses,$res);
  71. }
  72. ob_start();
  73. $handled = false;
  74. foreach($this->_paths as $k => $p){
  75. if($p->matches($url)){
  76. $handled = true;
  77. try{
  78. $p($res,$p->args($url));
  79. }catch(Exception $e){
  80. if(!is_null($onerror)){
  81. $onerror($res,$e);
  82. }else{
  83. throw $e;
  84. }
  85. }
  86. }
  87. }
  88. if(!$handled && !is_null($fn)){
  89. $fn($res,$url);
  90. }
  91. $res->output = ob_get_contents();
  92. ob_end_clean();
  93. return $res;
  94. }
  95. }
  96. ?>