abstrakt:<?php /*路由解析類 1.路由解析 2.請(qǐng)求分發(fā)*/ namespace pig; class Route { //路由信息 protected $route = []; //PATHINFO protected $pathInfo = []; //url參數(shù) protected
<?php /*路由解析類 1.路由解析 2.請(qǐng)求分發(fā)*/ namespace pig; class Route { //路由信息 protected $route = []; //PATHINFO protected $pathInfo = []; //url參數(shù) protected $params = []; //構(gòu)造方法初始化路由信息,給默認(rèn)值 public function __construct($route) { $this->route = $route; } //解析路由 public function parse($queryStr='') { //第一步:將查詢的字符串前后的/去掉,再按分隔符拆分到數(shù)組中 $queryStr = trim(strtolower($queryStr),'/'); //分割成數(shù)組 $queryArr = explode('/', $queryStr); //過濾掉非法字符 $queryArr = array_filter($queryArr); //第二步:解析出$queryArr數(shù)組中的內(nèi)容(模塊,控制器,操作,參數(shù)) switch(count($queryArr)) { //沒有參數(shù),則使用默認(rèn)的模塊、控制器、操作 case 0: $this->pathInfo=$this->route; break; //只有一個(gè)參數(shù):用戶提供了模塊,那么控制器和操作就使用默認(rèn)值 case 1: $this->pathInfo['module']=$queryArr[0]; break; //有兩個(gè)參數(shù),模塊和控制器,那么操作就用默認(rèn)值 $this->pathInfo['module']=$queryArr[0]; $this->pathInfo['controller']=$queryArr[1]; break; //有三個(gè)參數(shù) $this->pathInfo['module']=$queryArr[0]; $this->pathInfo['controller']=$queryArr[1]; $this->pathInfo['action']=$queryArr[2]; break; //對(duì)參數(shù)進(jìn)行處理 default: $this->pathInfo['module']=$queryArr[0]; $this->pathInfo['controller']=$queryArr[1]; $this->pathInfo['action']=$queryArr[2]; //從pathinfo數(shù)組的索引3開始,將剩余的元素全部作為參數(shù)處理 $arr=array_slice($queryArr,3); //鍵值必須成對(duì)出現(xiàn),所以每次遞增為2 for($i=0;$i<count($arr);$i=+2){ //如果沒有第二個(gè)參數(shù)(不成對(duì),有一個(gè)單的,判斷后面一個(gè)值是否存在就行),則放棄 if(isset($arr[$i+1])){ $this->params[$arr[$i]] = $arr[$i+1]; } } } //返回當(dāng)前路由類的實(shí)例對(duì)象,主要是方便鏈?zhǔn)秸{(diào)用:$route->parse()->worm()->print(),相當(dāng)于對(duì)象調(diào)用方法,只是省略了對(duì)象 return $this; } //請(qǐng)求分發(fā) public function dispath() { //生成的帶有命名空間的控制器名稱:app\模塊\controller\控制器類 //類名稱應(yīng)該與類文件所在的絕對(duì)路徑一一對(duì)應(yīng),這樣才可以實(shí)現(xiàn)自動(dòng)映射,方便自動(dòng)加載 //模塊名稱 $module = $this->pathInfo['module']; //控制器名稱(帶命名空間的)\\多的一個(gè)是轉(zhuǎn)義用的, $controller = '\app\\'.$module.'\controller\\'.ucfirst($this->pathInfo['controller']);//首字母大寫 die($controller); //操作名 $action = $this->pathInfo['action']; if(!method_exists($controller, $action)){//判斷類中是否存在方法 $action = $this->route['action']; //重定向到首頁(yè) header('Location:/'); } //將用戶的請(qǐng)求分發(fā)到指定的控制器和對(duì)應(yīng)的操作方法上 call_user_func_array([new $controller,$action], $this->params); } } //測(cè)試路由 $queryStr = $_SERVER['QUERY_STRING']; //echo $queryStr; //加載配置 $config = require 'config.php'; $route = new Route($config['route']); $route->parse($queryStr); /*echo '<br/>'; print_r($route->pathInfo); echo '<br/>'; print_r($route->params);*/ //加載類文件 require __DIR__.'/../app/admin/controller/Index.php'; $route->dispath();
Korrigierender Lehrer:韋小寶Korrekturzeit:2019-03-06 15:45:45
Zusammenfassung des Lehrers:路由還是比較重要的 關(guān)系的一些安全問題 后期記得要運(yùn)用到實(shí)際的開發(fā)中去哦