2015-12-04 37 views
-1

我想在此路由上創建一個404錯誤頁面。如何才能做到這一點?如何在路由系統中自定義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]); 
       } 
      } 
     } 
    } 


} 



?> 

回答

0

心目中的正則表達式,我只想你的所有其他路線後添加$route->add("/.+", function()...);

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


但你也可以計劃,評估一些邏輯的自定義404頁面不能夠找到一個correspondig路由時。

例如:

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行動