Routing class for tinyMvc


/ Published in: PHP
Save to your folder(s)



Copy this code and paste it in your HTML
  1. <?php
  2. class Router {
  3. function get()
  4. {
  5. //APP_BASE_URL is a constant i set for the framwork. It is the full url to the
  6. //root folder of the framework
  7. $my_url = $this->str_replace_once(APP_BASE_URL, '', $this->getfullurl());
  8.  
  9. //This removes the query string part of the url so that it can be evaluated
  10. if($_SERVER["QUERY_STRING"]) {
  11. $my_url = $this->str_replace_once("?" . $_SERVER["QUERY_STRING"], '', $my_url);
  12. }
  13. $my_url = $this->trimTrailingSlashes($my_url);
  14. $requestURI = explode('/', $my_url);
  15. $function = $requestURI[0];
  16. $parameters_str = '';
  17. for($i = 1; $i < count($requestURI); $i++){
  18. $parameters_str .= $requestURI[$i];
  19. if($i != count($requestURI)-1) {
  20. $parameters_str .= ', ';
  21. }
  22. }
  23.  
  24. //The function returns a PHP command as a string so that i can be used in eval()
  25. if($function){
  26. return '$this->'.$function.'('.$parameters_str.');';
  27. } else {
  28. return '$this->index();';
  29. }
  30. }
  31.  
  32.  
  33. //THESE FOLLOWING FUNCTIONS ARE JUST HELPERS
  34.  
  35. function str_replace_once($str_pattern, $str_replacement = '', $string){
  36. if (strpos($string, $str_pattern) !== false){
  37. $occurrence = strpos($string, $str_pattern);
  38. return substr_replace($string, $str_replacement, strpos($string, $str_pattern), strlen($str_pattern));
  39. }
  40. return $string;
  41. }
  42.  
  43. function trimTrailingSlashes($str){
  44. $str = trim($str);
  45. return $str == '/' ? $str : rtrim($str, '/');
  46. }
  47.  
  48. function getfullurl(){
  49. $s = empty($_SERVER["HTTPS"]) ? '' : ($_SERVER["HTTPS"] == "on") ? "s" : "";
  50. $protocol = substr(strtolower($_SERVER["SERVER_PROTOCOL"]), 0, strpos(strtolower($_SERVER["SERVER_PROTOCOL"]), "/")) . $s;
  51. $port = ($_SERVER["SERVER_PORT"] == "80") ? "" : (":".$_SERVER["SERVER_PORT"]);
  52. return $protocol . "://" . $_SERVER['SERVER_NAME'] . $port . $_SERVER['REQUEST_URI'];
  53. }
  54. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.