<?php
Class Router {
routing table
Private $routers = Array (
Array ("name" => "userlist", "pattern" => "Get/user", "Action" => "User#get"),
Array ("name" => "userinfo", "pattern" => "get/user/:s", "Action" => "User#getbyid"),
Array ("name" => "Useradd", "pattern" => "Post/user", "Action" => "User#add"),
Array ("name" => "Userupdate", "pattern" => "Update/user", "Action" => "User#update"),
Array ("name" => "Userdel", "pattern" => "Delete/user/:id", "Action" => "User#delete")
);
Entrance
Public Function Dispatch () {
$url = $_server["Request_uri"];
$method = $_server["Request_method"];
foreach ($this->routers as $router) {
$pattern = $router ["pattern"];
$pats = Explode ("", $pattern);
if (strcasecmp ($pats [0], $method) = = 0) {
Whether to match the current route
$params = $this->checkurl ($method, Strtolower ($url), Strtolower ($pats [1]));
if ($params!= null) {
Array_shift ($params);
$action = $router ["Action"];
Look for the first matching route to execute, and then return
return $this->invoke ($action, $params);
}
}
}
echo "404 Error";
Error 404
}
Private function Invoke ($action, $params) {
$acts = Explode ("#", $action);
$className = $acts [0]. " Action ";
$methodName = $acts [1];
$actionDir = DirName (__file__). Directory_separator. " Action ";
Load Action File
$classFile = $actionDir. Directory_separator $className. ". PHP ";
if (! file_exists ($classFile)) {
404 error
echo "404 error, no action found";
Return
} else {
Require "$classFile";
Using reflection to execute methods
$RC = new Reflectionclass ($className);
if (! $RC->hasmethod ($methodName)) {
404 error
echo "404 error, no method found";
Return
} else {
$instance = $RC->newinstance ();
$method = $RC->getmethod ($methodName);
$method->invokeargs ($instance, $params);
}
}
}
Regular match checking, and extracting parameters
Private Function Checkurl ($method, $str, $pattern) {
echo "Check $str with $pattern <br>";
$ma = Array ();
$pattern = LTrim (RTrim ($pattern, "/"));
$pattern = "/". Str_replace ("/", "\/", $pattern). " \/?$/";
$pattern = Str_replace (": S", "([^\/]+)", $pattern);
echo "Pattern $pattern <br>";
$str = "/\". $str. " $/";
if (Preg_match ($pattern, $str, $ma) > 0) {
return $ma;
}
return null;
}
}
?>