php - 如何修复此路由器类以包含 404 错误/页面?

标签 php oop url routes pathinfo

我正在为 php 练习开发一个简单的路由器,它已经发展了很多,但我发布了更简单的版本。

我的路由器类检查给定的 url 与当前服务器路径,如果匹配则返回内容。这工作正常,但问题是路由器运行了 3 次,因为我在routes.php 文件中调用了 router get() 方法 3 次。

例如,如果我想在路由不匹配时返回 404 错误,它将返回 3 次。未找到每条路线 1 次。解决这个问题的最佳方法是什么?

一如既往,非常感谢您的帮助。

路由器类别:

<?php
class Router {
    public $currentRoute = '/';
    public function __construct()
    {
        $this->getCurrentRoute();
    }
    public function getCurrentRoute()
    {
        if(isset($_SERVER['PATH_INFO'])) {
            $this->currentRoute = $_SERVER['PATH_INFO'];
        }
    }
    public function get($route, $content)
    {
        if($route == $this->currentRoute) {
            echo $content();
        }
    }
}

路线文件:

<?php

$router->get('/', function()
{
    return 'Index page';
});

$router->get('movies', function()
{
    return Cinematix\View::make('movies');
});

$router->get('users', function() 
{
    return 'The users collection page';
});

最佳答案

首先请注意,不推荐您的方法。查找经典MVC programming pattern是一个很好的开始方式。

如果您确实想按照开始使用匿名回调的方式进行操作,请继续阅读。

路由器类别:

class Router {
    public $currentRoute = '/';
    private $routes;

    public function __construct($routes)
    {
        $this->routes = $routes;
        $this->getCurrentRoute();
    }
    public function getCurrentRoute()
    {
        if(isset($_SERVER['PATH_INFO'])) {
            $this->currentRoute = $_SERVER['PATH_INFO'];
        }
    }
    public function route()
    {
        $route = $this->currentRoute;

        if (!isset($this->routes[$route])) {
            $route = '/404';
        }

        if (is_callable($this->routes[$route])) 
        {
            echo $this->routes[$route]();  
        }    
    }
}

路线文件:

$routes = array(
    '/' => function()
    {
        return 'Index page';
    },
    '/movies' => function()
    {
        return 'Movies';
    },
    '/users' => function() 
    {
        return 'The users collection page';
    },
    '/404' => function() 
    {
        return '404';
    }
);

$router = new Router($routes);
$router->route();

关于php - 如何修复此路由器类以包含 404 错误/页面?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28991005/

相关文章:

c++ - 我怎样才能让一个类实现一个接口(interface)....(C++)

php - 我应该将验证代码放在域模型中还是将其保留在外部?

php - Zend 中的 $adapter->query() 无法正常工作 - 字符串需要很长时间才能插入?

php - 检查 stdClass 对象在 PHP 中是否有 "entries"

php - 下拉设置 session 变量

php - 交响乐/独白 : Custom processor with FOSUserBundle data

java - 如何用 Java 替换 pdf 中的多个 url,最好使用 PdfBox

ios - 如何将输入数据的文本字段传递到 swift 上的 url

c# - 没有尾部斜杠的基本 Uri

php - Laravel - 语法错误,文件意外结束