2016-03-06 74 views

回答

0

該路由器只是一個概念證明,不應該在現實世界中使用。

它不是一個好的路由器,不要在真正的應用中使用它,它也不例外。我這樣做只是爲了好玩,並展示了簡單

至於爲什麼它不工作,那是因爲它看到/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'); 
     } 
    } 
} 
+0

我知道,源代碼是非常基本的。但是CodeIgniter/laravel/etc與/ user和/ user /具有相同的問題,因爲兩個不同的路由?感謝您的回答 –

+0

我不知道。可能不會。你應該閱讀他們的文檔。 –