I just finished rewriting my Router class. Any input would be much appreciated.
The class routes URLs based on a site.com/class/method/param/param/etc syntax.
One thing I've done differently is created a mechanism for basic templates to be loaded directly without the need for a controller. I often find pages such as /about/ do not require additional methodology, and setting up really baisc controllers just seems like a waste of time. Therefore, I have created a check for templates such as "_about.php" in the views folder, with the underscore denoting that it can be loaded directly.
The class also currently assumes an error class or template.
class Router{
public static function getPath($uri = null){
// set default uri
$uri = is_null($uri) ? $_SERVER['REQUEST_URI'] : $uri;
// remove possible query string
$uri = preg_replace('/\?(.*)/', '', $uri);
return explode('/',trim($uri,'/'));
}
public static function getQuery($uri = null){
// set default uri
$uri = is_null($uri) ? $_SERVER['REQUEST_URI'] : $uri;
// get query string
$query = substr($uri, strpos($uri,'?') + 1);
// parse into array
$q = array();
parse_str($query,$q);
return $q;
}
public static function follow($uri = null){
$path = self::getPath($uri);
// get controller and method, or set defaults of root and index
$controller = ($path[0] == "") ? 'root' : $path[0];
$method = ((count($path) > 1) && ($path[1] != "")) ? $path[1] : null;
// see if controller is a static page, only possible if no method specified
if(is_null($method) && file_exists(APPLICATION_DIR . '/views/_' . $controller . '.php')){
include APPLICATION_DIR . '/views/_' . $controller . '.php';
}
else if(file_exists(APPLICATION_DIR . '/controllers/' . $controller . '.php')){ // see if controller exists
// load controller class
include_once APPLICATION_DIR . '/controllers/' . $controller . '.php';
// if method is empty or doesn't exist, it defaults to "index"
if(is_null($method) || !method_exists($controller,$method)) {
$method = "index";
}
if(method_exists($controller, $method)){
$c = new $controller();
$c->$method();
}
else{
self::follow('e404');
}
}
else{
self::follow('e404');
}
}
}