【发布时间】:2016-06-19 17:27:30
【问题描述】:
我尝试为 Web 应用程序制作路由器,但是当我输入 /user 时,它与 /user/ 不一样 源代码是Github - 140 Chars Router
谁能解释一下,也许给我一个可以解释这个问题的简单代码?
【问题讨论】:
我尝试为 Web 应用程序制作路由器,但是当我输入 /user 时,它与 /user/ 不一样 源代码是Github - 140 Chars Router
谁能解释一下,也许给我一个可以解释这个问题的简单代码?
【问题讨论】:
该路由器只是概念验证,不应在现实世界中使用。
它根本不是一个好的路由器,不要在真正的应用程序上使用它,它也没有处理异常。我这样做只是为了好玩并展示简单性
至于为什么不起作用,是因为它把/user和/user/看作是两条不同的路由。您必须添加两条路由才能让路由器同时捕获它们:
function route_user() { echo 'User route'; }
$router->a('/user', 'route_user');
$router->a('/user/', 'route_user');
路由器非常基本。它只是添加路由,然后将其与当前路径匹配。它不做任何其他事情。
这是路由器的扩展和注释版本:
class Router
{
// Collection of routes
public $routes = [];
// Add a path and its callback to the
// collection of routes
function add($route, callable $callback) {
$this->routes[$route] = $callback;
}
// Looks at the current path and if it finds
// it in the collection of routes then runs
// the associated function
function execute() {
// The server path
$serverVariables = $_SERVER;
$serverKey = 'PATH_INFO';
// Use / as the default route
$path = '/';
// If the server path is set then use it
if (isset($serverVariables[$serverKey])) {
$path = $serverVariables[$serverKey];
}
// Call the route
// If the route does not exist then it will
// result in a fatal error
$this->routes[$path]();
}
}
一个更实用的版本是这样的:
class Router {
public $routes = [];
function add($route, callable $callback) {
// Remove trailing slashes
$route = rtrim($route, '/');
if ($route === '') {
$route = '/';
}
$this->routes[$route] = $callback;
}
function execute() {
// Only call the route if it exists and is valid
$path = isset($_SERVER['PATH_INFO']) ? $_SERVER['PATH_INFO'] : '/';
if (isset($this->routes[$path]) and is_callable($this->routes[$path])) {
$this->routes[$path]();
} else {
die('Route not found');
}
}
}
【讨论】: