abstract:<?php /** *路由、分发类 */ namespace pig; class Route { // protected $route = []; public $route = []; //&nbs
<?php /** *路由、分发类 */ namespace pig; class Route { // protected $route = []; public $route = []; // protected $pathInfo=[]; public $pathInfo=[]; // protected $params=[]; public $params=[]; public function __construct($route) { $this->route=$route; } public function parse($queryStr='') { $queryStr=trim(strtolower($queryStr),'/'); $queryArr=explode('/',$queryStr); $queryArr=array_filter($queryArr); switch (count($queryArr)) { 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){ if (isset($arr[$i+1])){ $this->params[$arr[$i]]=$arr[$i+1]; } } break; } return $this; } public function dispatch() { $module=$this->pathInfo['module']; $controller='\app\\'.$module.'\controller\\'.$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); } } //引入配置文件 $config=require 'config.php'; //路由配置,默认信息; $route=new Route($config['route']); //显示默认模块名,操作名,方法名 var_dump( $route->route); //解析显示用户提交的模块名,操作名,方法名和参数 var_dump($route->parse($_SERVER['REQUEST_URI'])); //解析出用户提交的模块名,操作名,方法名; var_dump($route->pathInfo);
Correcting teacher:查无此人Correction time:2019-05-13 09:47:08
Teacher's summary:完成的不错。映射属于高端技术。要好好练习,继续加油。