Return to Snippet

Revision: 42272
at March 2, 2011 16:32 by robertnduati


Initial Code
<?php 
class Router {
	function get() 
	{
		//APP_BASE_URL is a constant i set for the framwork. It is the full url to the
		//root folder of the framework
		$my_url = $this->str_replace_once(APP_BASE_URL, '', $this->getfullurl());
		
		//This removes the query string part of the url so that it can be evaluated
		if($_SERVER["QUERY_STRING"]) {
			$my_url = $this->str_replace_once("?" . $_SERVER["QUERY_STRING"], '', $my_url);
		}
		$my_url = $this->trimTrailingSlashes($my_url);
		$requestURI = explode('/', $my_url);
		$function = $requestURI[0];
		$parameters_str = '';
		for($i = 1; $i < count($requestURI); $i++){
			$parameters_str .= $requestURI[$i];
			if($i != count($requestURI)-1) {
				$parameters_str .= ', ';
			}
		}
		
		//The function returns a PHP command as a string so that i can be used in eval()
		if($function){
			return '$this->'.$function.'('.$parameters_str.');';
		} else {
			return '$this->index();';
		}
	}
	
	
	//THESE FOLLOWING FUNCTIONS ARE JUST HELPERS
	
	function str_replace_once($str_pattern, $str_replacement = '', $string){
		if (strpos($string, $str_pattern) !== false){
			$occurrence = strpos($string, $str_pattern);
			return substr_replace($string, $str_replacement, strpos($string, $str_pattern), strlen($str_pattern));
		}
		return $string;
	}
	
	function trimTrailingSlashes($str){
		$str = trim($str);
		return $str == '/' ? $str : rtrim($str, '/');
	}
	
	function getfullurl(){
		$s = empty($_SERVER["HTTPS"]) ? '' : ($_SERVER["HTTPS"] == "on") ? "s" : "";
		$protocol = substr(strtolower($_SERVER["SERVER_PROTOCOL"]), 0, strpos(strtolower($_SERVER["SERVER_PROTOCOL"]), "/")) . $s;
		$port = ($_SERVER["SERVER_PORT"] == "80") ? "" : (":".$_SERVER["SERVER_PORT"]);
		return $protocol . "://" . $_SERVER['SERVER_NAME'] . $port . $_SERVER['REQUEST_URI'];
	}
}

Initial URL

                                

Initial Description

                                

Initial Title
Routing class for tinyMvc

Initial Tags

                                

Initial Language
PHP