摘要:class Route{ //路由配置模塊 // protected $route=[]; public $route=[]; //PATHINO // protected $pathInfo=[]; &nb
class Route{ //路由配置模塊 // protected $route=[]; public $route=[]; //PATHINO // protected $pathInfo=[]; public $pathInfo=[]; //參數(shù) // protected $params=[]; public $params=[]; public function __construct($route){ //路由初始化配置 return $this->route=$route; } //解析路由 public function parse($queryString=''){ $queryString=trim($queryString,'/');//將獲得的字符串去掉斜杠 /admin/user/show/add $queryArr=explode('/',$queryString); //將去掉斜杠的字符串進行切割 // $queryArr=array_filter($queryArr);//過濾0 //解析出$queryArr數(shù)組中的內(nèi)容(模塊,控制器,操作,參數(shù)) switch (count($queryArr)){ case 0;//數(shù)組中沒有參數(shù)的情況。地址默認為當前地址 $this->pathInfo=$this->route; break; case 1;//數(shù)組中只有一個參數(shù)的情況 $this->pathInfo['model']=$queryArr[0]; break; case 2;//2個參數(shù),模塊和控制器是自定義的,操作是默認的。 $this->pathInfo['model']=$queryArr[0]; $this->pathInfo['controller']=$queryArr[1]; break; case 3;//3個參數(shù)。模塊,控制器,操作全部自定義:全部來自用戶對實際請求 $this->pathInfo['model']=$queryArr[0]; $this->pathInfo['controller']=$queryArr[1]; $this->pathInfo['action']=$queryArr[2]; break; //如果是非法或者是不存在的訪問,對參數(shù)進行處理 default; $this->pathInfo['model']=$queryArr[0]; $this->pathInfo['controller']=$queryArr[1]; $this->pathInfo['action']=$queryArr[2]; //從pathInfo的數(shù)組3開始索引,將剩余的元素全部作為參數(shù)進行處理 $arr=array_slice($queryArr,3); for($i=0;$i<count($arr);$i+=2){ if(isset($arr[$i+1])){//如果數(shù)組中沒有第二個參數(shù)則放棄 $this->params[$arr[$i]]=$arr[$i+1]; } } break; } //返回當前路由的實例對象,主要是方便鏈式調(diào)用:$route->parse()->worm()->print() return $this; } //請求分發(fā) public function dispatch(){ //生成的帶有命名空間的控制器類名稱:app\模塊\controller\控制器類 //類名稱應該與類文件所在的絕對路徑一一對應,這樣才可以實現(xiàn)自動映射,方便自動加載 //獲取模塊名稱 $module=$this->pathInfo['model']; //獲取控制器名稱 $controller='app\\'.$module.'\\controller\\'.ucfirst($this->pathInfo["controller"]); //獲取操作 $action=$this->pathInfo['action']; if(!method_exists($controller,$action)){ $action=$this->pathInfo['action']; header('Location: /'); } //將用戶請求分發(fā)到指定到控制和操作方法上 return call_user_func_array([new $controller,$action],$this->params); } //獲取pathInfo public function getPathInfo(){ return $this->pathInfo; } //獲取模塊 public function getModel(){ return $this->pathInfo['model']? :$this->route['module']; } //獲取控制器名稱 public function getController(){ $controller='app\\'.$this->getModel().'\\controller\\'.ucfirst($this->pathInfo["controller"]); } } //測試路由器 echo $queryString=$_SERVER['QUERY_STRING']; echo '<hr>'; echo $queryString=trim($queryString,'/'); echo'<hr>'; print_r($queryArr=explode('/',$queryString)); echo'<hr>'; echo'<pre>'; $config=require __DIR__.'/config.php'; $rote=new Route($config['route']); $rote->parse($queryString); echo'<hr>'; //測試請求分發(fā) require __DIR__.'/../app/admin/controller/Index.php'; echo $rote->dispatch();
批改老師:韋小寶批改時間:2019-02-28 09:18:43
老師總結(jié):寫的很棒 路由對于一個項目來說還是比較重要的 它關系的安全性