如何在路由系统中制作自定义404页面


How to make custom 404 page in routing system

我想在这个路由上创建一个404错误页面。如何做到这一点?

index.php

<?php
    include 'route.php';
    include 'control/about.php';
    include 'control/home.php';
    include 'control/contact.php';
    $route = new route();
    $route->add('/', function(){
        echo 'Hello, this is home pageeees';
    });
    $route->add('/about', 'about');
    $route->add('/contact', 'contact');
    echo '<pre>';
    print_r($route);
    $route->submit();
?>

route.php

<?php

class route 
{   
    private $_uri = array();
    private $_method = array();
    /**
    *Builds a collection of internal URL's to look for
    *@parameter type $uri
    */
    public function add($uri, $method = null)
    {
        $this->_uri[] = '/' . trim($uri, '/');
        if($method != null){
            $this->_method[] = $method;
        }
    }
    /**
    *Makes the thing run! 
    */
    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]);
                }
            }
        }
    }

}

?>

记住的regex我只会在所有其他路由之后添加$route->add("/.+", function()...);

证明:https://3v4l.org/nk5PZ


但您也可以编程一些逻辑,当无法找到相应的路由时,评估自定义404页面。

例如:

private $_notFound;
public function submit() {
    $uriGetParam = isset($_GET['uri'])? '/' . $_GET['uri'] : '/';
    $matched = false;
    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]);
            }
            $matched = true;
        }
    }
    if(!$matched) {
        if(isset($this->_notFound)) {
            if(is_string($this->_notFound)) {
                $action = $this->_notFound;
                new $action();
            } else {
                call_user_func($this->_notFound);
            }
        }
    }
}
public function notFound($callback) {
    $this->_notFound = $callback;
}

然后您必须通过$route->notFound(function... or "class"); 添加404操作