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

时间:2015-12-04 19:30:11

标签: php class routing

我想在此路由上创建一个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]);
                }
            }
        }
    }


}



?>

1 个答案:

答案 0 :(得分:0)

考虑到正则表达式我只想在所有其他路线之后添加func someFunc(value:UInt8) -> SomeType { switch value { case 0x00: return SomeType.foo() case 0x13: return SomeType.bar() default: break // BUT I WANT AN ERROR HERE } }

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

但是你也可以编写一些逻辑来评估自定义404页面时无法找到相应的路由。

例如:

$route->add("/.+", function()...);

然后您必须按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; }

添加404动作