abstract:<?php /** * Created by PhpStorm. * User: Administrator * Date: 2019/6/4 * Time: 17:50 */ class Route{ &
<?php /** * Created by PhpStorm. * User: Administrator * Date: 2019/6/4 * Time: 17:50 */ class Route{ protected $route = []; public $pathInfo = []; public $params = []; public function __construct($route) { $this->route=$route; } //解析路由 public function parse($queryStr=''){ //去除前后/ $queryStr = trim(strtolower($queryStr),'/'); //切割 $queryArr = explode('/',$queryStr); $queryArr = array_filter($queryArr); //解析出queryArr的模塊、控制器、操作、參數(shù) switch (count($queryArr)){ //如果沒有指向默認(rèn)控制器 case 0: $this->pathInfo = $this->route; break; case 1: $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: $this->pathInfo['module']=$queryArr[0]; $this->pathInfo['controller']=$queryArr[1]; $this->pathInfo['action']=$queryArr[2]; $arr = array_slice($queryArr,3); for($i = 0;$i<count($arr);$i+=2){ //如果沒有第二個(gè)參數(shù),則放棄 if (isset($arr[$i+1])) { $this->params[$arr[$i]] = $arr[$i+1]; } } break; } return $this; } //請求分發(fā) public function dispatch(){ $module = $this->pathInfo['module']; $controller='app\\'.$module.'\controller\\'. ucfirst($this->pathInfo['controller']); $action = $this->pathInfo['action']; if (!method_exists($controller, $action)) { $action = $this->route['action']; header('Location: /'); } return call_user_func_array([new $controller,$action],$this->params); } } //測試路由 $queryStr = $_SERVER['QUERY_STRING']; echo $queryStr; echo '<hr>'; echo '<pre>'; print_r(explode('/',$queryStr)); echo '<hr>'; $config = require 'config.php'; $route = new Route($config['route']); $route->parse($queryStr); print_r($route->pathInfo); print_r($route->params);
Correcting teacher:查無此人Correction time:2019-06-05 09:35:41
Teacher's summary:完成的不錯(cuò)。編程有很多設(shè)計(jì)模式,多了解,對以后工作幫助很大。繼續(xù)加油。