摘要:<?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的模块、控制器、操作、参数
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\\'. 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);
批改老师:查无此人批改时间:2019-06-05 09:35:41
老师总结:完成的不错。编程有很多设计模式,多了解,对以后工作帮助很大。继续加油。