Skip to content

Instantly share code, notes, and snippets.

@KlonD90
Created May 13, 2012 20:15
Show Gist options
  • Save KlonD90/2690009 to your computer and use it in GitHub Desktop.
Save KlonD90/2690009 to your computer and use it in GitHub Desktop.
Router for php
<?php
class User{
public function bred($a,$b){
echo '<b>'.$a.'</b>'."<i>{$b}</i>";
}
}
class service{
public function __get($name) {
if($this->$name)
return $name;
else{
$this->$name = new $name();
return $this->$name;
}
}
}
$service = new service();
$method = $_SERVER['REQUEST_METHOD'];
$url = $_SERVER['REQUEST_URI'];
$urlMapping = array(
'GET' => array(
'/' => array(
'controller' => 'List#list'
),
'/page/:page' => array(
'controller' => 'List#list'
),
'/user/:login' => array(
'controller' => 'User#login'
),
'/user/:login/edit/:f' => array(
'controller' => 'User#edit'
),
'/user/:login/:bred' => array(
'controller' => 'User#bred'
),
'/user/:login/edit/f' => array(
'controller' => 'User#f'
),
'/user/:login/:bred/f' => array(
'controller' => 'User#ef'
),
'/post/add' => array(
'controller' => 'Post#add'
),
'/post/:id' => array(
'controller' => 'Post#show'
)
),
'POST' => array(
'/user/:login/edit' => array(
'controller' => 'User#doEdit',
'params' => array('nick', 'email', 'pass')
),
'/post/add' => array(
'controller' => 'Post#doAdd',
'params' => array('title', 'text')
)
)
);
$mapping = $urlMapping[$method];
$routeData = proccessRouting($mapping, $url);
if(!is_array($routeData))
pageNotFound();
$class = $routeData['class'];
$obj = $service->$class;
call_user_func_array(array($obj,$routeData['method']),$routeData['params']);
function proccessRouting($mapping, $url) {
$url = explode('/',$url);
$maps = array_keys($mapping);
$urlSize = count($url);
$routing = array();
foreach ($maps as $map) {
$mapArray = explode('/', $map);
if (count($mapArray) === $urlSize) {
$equal = true;
for ($i = 1; $i < $urlSize; $i++) {
$mapElement = $mapArray[$i];
if (substr($mapElement, 0, 1) == ':')
continue;
if ($mapElement != $url[$i]) {
$equal = false;
break;
}
}
if ($equal)
$routing[] = $map;
}
}
if(count($routing)==0)
return false;
$route = array_reduce($routing, function($best,$route){
if(substr_count($route,':') < substr_count($best,':'))
return $route;
else
return $best;
},$routing[0]);
$params = array();
$routeArray = explode('/',$route);
for($i=1;$i<$urlSize;$i++){
if (substr($routeArray[$i], 0, 1) == ':')
$params[] = $url[$i];
}
$needParams = $mapping[$route]['params'];
if($needParams)
foreach ($needParams as $postParam) {
$params[] = $_POST[$postParam];
}
$controller = explode('#',$mapping[$route]['controller']);
$class = $controller[0];
$method = $controller[1];
return array('class'=>$class,'method'=>$method,'params'=>$params);
}
function pageNotFound(){
echo 'not found';
exit();
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment