路由类,从url到类方法的映射

Original 2019-03-06 14:45:35 195
abstract:<?php /*路由解析类 1.路由解析 2.请求分发*/ namespace pig; class Route { //路由信息 protected $route = []; //PATHINFO protected $pathInfo = []; //url参数 protected 
<?php
/*路由解析类
1.路由解析
2.请求分发*/

namespace pig;

class Route
{
	//路由信息
	protected $route = [];
	//PATHINFO
	protected $pathInfo = [];
	//url参数
	protected $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;
			//有两个参数,模块和控制器,那么操作就用默认值
			
				$this->pathInfo['module']=$queryArr[0];	
				$this->pathInfo['controller']=$queryArr[1];	
				break;
			//有三个参数
			    $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];
				//从pathinfo数组的索引3开始,将剩余的元素全部作为参数处理
				$arr=array_slice($queryArr,3);
				//键值必须成对出现,所以每次递增为2
				for($i=0;$i<count($arr);$i=+2){
					//如果没有第二个参数(不成对,有一个单的,判断后面一个值是否存在就行),则放弃
					if(isset($arr[$i+1])){
						$this->params[$arr[$i]] = $arr[$i+1];
					}
				}
		}
		//返回当前路由类的实例对象,主要是方便链式调用:$route->parse()->worm()->print(),相当于对象调用方法,只是省略了对象
		return $this;
	}
    
	//请求分发
	public function dispath()
	{
		//生成的带有命名空间的控制器名称:app\模块\controller\控制器类
		//类名称应该与类文件所在的绝对路径一一对应,这样才可以实现自动映射,方便自动加载
		//模块名称
		$module = $this->pathInfo['module'];
		//控制器名称(带命名空间的)\\多的一个是转义用的,
		$controller = '\app\\'.$module.'\controller\\'.ucfirst($this->pathInfo['controller']);//首字母大写
		die($controller);
		//操作名
		$action = $this->pathInfo['action'];
		if(!method_exists($controller, $action)){//判断类中是否存在方法
			$action = $this->route['action'];
		     //重定向到首页
		     header('Location:/');
		}
		//将用户的请求分发到指定的控制器和对应的操作方法上
		call_user_func_array([new $controller,$action], $this->params);
	}
}

//测试路由
$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();


Correcting teacher:韦小宝Correction time:2019-03-06 15:45:45
Teacher's summary:路由还是比较重要的 关系的一些安全问题 后期记得要运用到实际的开发中去哦

Release Notes

Popular Entries