abstrakt:<?php // 路由解析類 namespace Pigs; class Routes { // 默認(rèn)路由 protected $route = []; // pa
<?php // 路由解析類 namespace Pigs; class Routes { // 默認(rèn)路由 protected $route = []; // pathInfo 信息 protected $pathInfo = []; // Url參數(shù) protected $params = []; // 創(chuàng)建構(gòu)造方法 public function __construct($route) { $this->route = $route; } // 解析路由 public function parse($queryStr='') { // 處理字符串信息,去掉左右兩邊的/ 并把字母全部轉(zhuǎn)換成小寫 $queryStr = trim(strtolower($queryStr),'/'); // 將字符串分割成數(shù)組 $queryArr = explode('/',$queryStr); // 判斷解析的數(shù)組個(gè)數(shù),獲?。K,控制器,操作,參數(shù)) switch(count($queryArr)) { // 如果為0 則使用默認(rèn)路由 case 0: $this->pathInfo = $this->route; break; case 1: // 只有一個(gè)數(shù)組時(shí),取回的就是模塊 $this->pathInfo['module'] = $queryArr[0]; break; case 2: $this->pathInfo['module'] = $queryArr[0];// 模塊 $this->pathInfo['controller'] = $queryArr[1];// 控制器 break; case 3: $this->pathInfo['module'] = $queryArr[0];// 模塊 $this->pathInfo['controller'] = $queryArr[1];// 控制器 $this->pathInfo['action'] = $queryArr[2];// 操作 break; default :// 默認(rèn)情況 $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ì)必須成對(duì)出現(xiàn),所以每次遞增為2 $count = count($arr); for($i=0;$i<$count;$i+=2) { // 如果沒有第二個(gè)參數(shù),則放棄 if(isset($arr[$i+1])) { $this->params[$arr[$i]] = $arr[$i+1]; } } break; } // 返回當(dāng)前路由的實(shí)例對(duì)象,主要是方便鏈?zhǔn)秸{(diào)用:$route->parse return $this; } // 請(qǐng)求分發(fā) public function dispatch() { // 獲取模塊 $module = $this->pathInfo['module']; // 獲取控制器 拼接路徑,給控制器首字母轉(zhuǎn)換大寫 $controller = 'app\\'.$module.'\controller\\'.ucfirst($this->pathInfo['controller']); // 獲取操作 $action = $this->pathInfo['action']; // 判斷是否存在類中的操作方法 if(!method_exists($controller,$action)) { // 不存在 則使用默認(rèn)操作 $action = $this->route['action']; // 重定向 header('Location:/'); } // 使用call_user_func_array(); 將用戶的請(qǐng)求分發(fā)到指定的控制器和方法上 return call_user_func_array([new $controller,$action],$this->params); } // 獲取pathInfo public function getPathInfo() { return $this->pathInfo; } // 獲取模塊 public function getModule() { return $this->pathInfo['module']; } // 獲取控制器名稱 public function getController() { return 'app\\'.$this->getModule().'\controller\\'.ucfirst($this->pathInfo['controller']); } } // 獲取地址信息 $queryStr = $_SERVER['QUERY_STRING']; // 導(dǎo)入路由信息 $config = require 'config.php'; // 傳入默認(rèn)路由 $route = new Routes($config['route']); echo '<pre>'; $rs = $route->parse($queryStr); require __DIR__.'/../app\admin\controller\Index.php'; // 測(cè)試請(qǐng)求分發(fā) print_r($rs->dispatch()); ?>
Korrigierender Lehrer:天蓬老師Korrekturzeit:2019-04-14 22:03:32
Zusammenfassung des Lehrers:這個(gè)課程是我錄制, 如果我沒記錯(cuò), 你應(yīng)該是把教學(xué)源碼直接復(fù)制過來發(fā)布的, 不知你是否明白了原理, 至少要寫點(diǎn)學(xué)習(xí)體會(huì)吧....
為了不影響后面的學(xué)習(xí), 這次先通過, 下次不要這么隨意了