Created
July 13, 2011 20:33
-
-
Save saltybeagle/1081254 to your computer and use it in GitHub Desktop.
Simple router idea, uses array of routes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class Router | |
{ | |
protected static $routes = array(); | |
public static function route($requestURI, $options = array()) | |
{ | |
if (!empty($_SERVER['QUERY_STRING'])) { | |
$requestURI = substr($requestURI, 0, -strlen(urldecode($_SERVER['QUERY_STRING'])) - 1); | |
} | |
// Trim the base part of the URL | |
$requestURI = substr($requestURI, strlen(parse_url(Controller::getURL(), PHP_URL_PATH))); | |
$routes = self::getRoutes(); | |
if (isset($options['view'], $routes[$options['view']])) { | |
$options['model'] = $routes[$options['view']]; | |
return $options; | |
} | |
if (empty($requestURI)) { | |
// Default view/homepage | |
return $options; | |
} | |
foreach ($routes as $route_exp=>$model) { | |
if ($route_exp[0] == '/' | |
&& preg_match($route_exp, $requestURI, $matches)) { | |
$options += $matches; | |
$options['model'] = $model; | |
return $options; | |
} | |
} | |
$options['model'] = false; | |
return $options; | |
} | |
public static function getRoutes() | |
{ | |
return self::$routes; | |
} | |
/** | |
* Set the routes | |
* | |
* @param array(preg => ModelName) $routes Associative array of routes | |
*/ | |
public static function setRoutes($routes) | |
{ | |
self::$routes = $routes; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment