I have finished my router and would like your thoughts on anything that may be inefficient of could be done better!:
class Router {
public $start_page = 'Dashboard' ; // Change to your home/default page.
public $staticRoutes = array(
'alias' => 'ActualController',
) ;
function __construct()
{
$url = substr(rtrim($_SERVER['REQUEST_URI'], '/'), 6) ;
if($url)
{
$components = explode('/', $url, 3) ;
if(array_key_exists($class, $this->staticRoutes))
{
$class = $this->staticRoutes[$class] ;
} else {
$class = preg_replace('/[^a-z-]/', '', $components[0]) ;
}
if(class_exists($class))
{
if(isset($components[1])) // has method...
{
$method = preg_replace('/[^a-z-]/', '', $components[1]) ;
if(method_exists($class, $method))
{
if(isset($components[2])) // has params...
{
$params = explode('/', $components[2]) ;
call_user_func_array(array($class, $method), $params) ;
} else {
$controller = new $class ;
$controller->$method() ;
}
} else {
$e = 'Method '.$components[1].' does not exist.' ;
new Error(array('msg' => $e), 'Method Error') ;
}
} else { // No method so just go to default index if exists...
$controller = new $class ;
if(method_exists($controller, 'index'))
{
$controller->index() ;
} else {
$e = 'Class '.$class.' has no default index method.' ;
new Error(array('msg' => $e), 'Class Index Error') ;
}
}
} else {
$e = 'Class '.$components[0].' does not exist.' ;
new Error(array('msg' => $e), 'Class Error') ;
}
} else {
$controller = new $this->start_page ;
$controller->index() ;
}
}
}
Note that I have not implements the static routes functionality yet.