摘要:<?php class Route { //保存路由配置信息 protected $route = []; //保存url路径信息 protected
<?php
class Route
{
//保存路由配置信息
protected $route = [];
//保存url路径信息
protected $pathinfo = [];
//保存url参数
protected $param = [];
public function __construct($route)
{
$this->route = $route;
}
//解析路由
//http://frame.io/[index.php]/admin/Index/index
public function parse($url)
{
if(strpos($url,'.php')){
$queryStr = strchr($url,'.php');
$queryStr = trim(substr($queryStr,4),'/');
}else{
$domainLen = strlen($_SERVER['SERVER_NAME']);
$queryStr = strchr($url,$_SERVER['SERVER_NAME']);
$queryStr = trim(substr($queryStr,$domainLen),'/');
}
$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];
//处理参数
$paramArr = array_slice($queryArr,3);
for($i=0;$i<count($paramArr);$i+=2){
if(!empty($paramArr[$i+1])){
$this->param[$paramArr[$i]] = $paramArr[$i+1];
}
}
}
return $this;
}
//路由分发
public function dispatch()
{
$module = $this->getModule();
$controller = $this->getController();
if(!method_exists(new $controller,$this->pathinfo['action'])){
header('Location:/');
}
call_user_func_array([new $controller,$this->getAction()],$this->param);
}
public function getModule()
{
return $this->pathinfo['module'];
}
public function getParam()
{
return $this->param;
}
public function getController()
{
$module = $this->getModule();
$controller = 'app\\'.$module.'\controller\\'.ucfirst($this->pathinfo['controller']);
return $controller;
}
public function getAction()
{
return $this->pathinfo['action'];
}
}
$url = 'http://frame.io/admin/Index/index/name/peter/age/30';
$config = require __DIR__.'/config.php';
$route = new Route($config['route']);
$route->parse($url);
require __DIR__.'/../app/admin/controller/Index.php';
$route->dispatch();
批改老师:天蓬老师批改时间:2019-01-08 17:32:33
老师总结:你完全可以用自己的方式进行测试, 没有必要照抄老师的代码,
这个框架你写完, 基本上对现代框架的运行流程就理解了, 再学其它商业框架,就非常轻松了, 因为你从底层理解了