使用漂亮的 url 将用户重定向到 404 页面

Redirecting users to a 404 page by using pretty urls

我正在做一个 mvc 项目只是为了好玩。 漂亮的 url 已经可以工作了,但是我找不到一个好的方法来使用我的代码将访问者发送到 404 页面,以防人们正在寻找的页面不存在。

class Route
{
       private $_uri = array();
       private $_method = array();

    /*
     * Builds a collection of internal URL's to look for
     * @param type $uri
     */
    public function add($uri, $method = null)
    {
        $this->_uri[] = '/' . trim($uri, '/');

        if($method != null){
            $this->_method[] = $method;
        }
    }

    public function submit()
    {

        $uriGetParam = isset($_GET['uri']) ? '/' . $_GET['uri'] : '/';

        foreach($this->_uri as $key => $value){
            if(preg_match("#^$value$#",$uriGetParam)){
                if(is_string($this->_method[$key])){
                    $useMethod = $this->_method[$key];
                    new $useMethod();
                }
                else{
                    call_user_func($this->_method[$key]);
                }
            }
        }
    }

}

我没有彻底分析你的代码(我不能,不确定你用 ->add 添加的示例路由/方法是什么),但解决方案对我来说似乎很简单:

public function submit()
{

    $uriGetParam = isset($_GET['uri']) ? '/' . $_GET['uri'] : '/';
    $routeFound = false;
    foreach($this->_uri as $key => $value){
        if(preg_match("#^$value$#",$uriGetParam)){
            if(is_string($this->_method[$key])){
                $routeFound = true; 
                $useMethod = $this->_method[$key];
                new $useMethod();
            }
            else{
                $routeFound = true; 
                call_user_func($this->_method[$key]);
            }
        }
    }
    if(!$routeFound){ 
        http_response_code(404);
        echo 'ooooh, not found'; 
        //or:
        include('404.php');
        die();
    }
}

p.s。 http_response_code 是内置函数:

https://secure.php.net/manual/en/function.http-response-code.php

编辑:您可以将以 'http_response_code(404);' 开头的代码放到一个单独的函数中,然后调用它。