Created
December 5, 2014 16:30
-
-
Save dennisdegryse/14b696f9877189bb79e2 to your computer and use it in GitHub Desktop.
Basic URI router concept
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 | |
include_once("/path/to/Router.php"); | |
// define a fallback uri | |
if (!array_key_exists('uri', $_GET)) | |
$_GET['uri'] = 'home'; | |
$router = new Router(); | |
$router->route($uri); |
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 { | |
private $_defaultParameters; | |
public Router($defaultParameters) { | |
$this->_defaultParameters = $defaultParameters; | |
} | |
public function route($uri) { | |
// Sanitize the uri | |
if (strstr($uri, '?') === FALSE) | |
$uri .= '?'; | |
// break URI apart on the first ?-character: left hand is the action (based on file name), right hand is the query string | |
list($action, $queryString) = explode('?', $uri, 2); | |
// parse the query string | |
$parameters = parse_str($queryString) | |
// keep track of missing parameters | |
$hasMissingParameters = false; | |
// fill in missing parameters | |
foreach ($this->_defaultParameters as $parameterName => $defaultValue) | |
if (!array_key_exists($parameterName, $parameters)) { | |
$parameters[$parameterName] = $defaultValue; | |
$hasMissingParameters |= true; | |
} | |
if ($hasMissingParameters) { | |
$uri = $this->_buildUri($action, $parameters); | |
header('Location: ' . $uri); | |
} else { | |
try { | |
$this->_mapAction($action, $parameters); | |
} catch (Exception e) { | |
// Routing failed. Redirect to a stable page and log the error. | |
} | |
} | |
} | |
private function _buildUri($action, $parameters) { | |
$queryString = http_build_query($parameters); | |
return $action . '?' . $queryString; | |
} | |
private function _mapAction($action, $parameters) { | |
// Use reflection or autoloader to map your action to a specific controller method and supply the necessary parameters. | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment