【问题标题】:Routing For Web Application [closed]Web应用程序的路由[关闭]
【发布时间】:2016-06-19 17:27:30
【问题描述】:

我尝试为 Web 应用程序制作路由器,但是当我输入 /user 时,它与 /user/ 不一样 源代码是Github - 140 Chars Router

谁能解释一下,也许给我一个可以解释这个问题的简单代码?

【问题讨论】:

    标签: php routing


    【解决方案1】:

    该路由器只是概念验证,不应在现实世界中使用。

    它根本不是一个好的路由器,不要在真正的应用程序上使用它,它也没有处理异常。我这样做只是为了好玩并展示简单性

    至于为什么不起作用,是因为它把/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');
            }
        }
    }
    

    【讨论】:

    • 我知道,源代码非常基础。但是 CodeIgniter/laravel/etc 是否有像 /user 和 /user/ 一样的问题作为两个不同的路由?谢谢你的回答
    • 我不知道。可能不是。你应该阅读他们的文档。
    猜你喜欢
    • 1970-01-01
    • 2012-09-16
    • 2012-01-09
    • 2023-03-14
    • 2016-02-17
    • 2021-04-02
    • 1970-01-01
    • 2021-05-08
    • 2015-03-10
    相关资源
    最近更新 更多