index.php文件中的内容
$config=[
'route'=>[
'module'=>'admin',
'controller'=>'Index',
'action'=>'index'
]
];
class Route
{
// 默认路由
private $route=[];
// 默认控制器
private $pathinfo=[];
// 默认参数
private $params=[];
// 实例化时,配置默认路由
public function __construct($route)
{
$this->route=$route;
}
public function parse($path='')
{
// 获取路由
// $path=$_SERVER['QUERY_STRING'];
// 1.去掉首位的/
// 2.全部变成小写
// 3.根据/切割成数组
// 4.去掉数组两侧的空值
$path=trim($path,'/');
$path=strtolower($path);
$path=explode('/',$path);
// $path=array_filter($path);
// echo '<pre>'.print_r($path,true).'</pre>';
/*
* 判断$path的长度
* 0:没有参数部分时进入首页
* 1、2、3:分别代表只有模块、控制器、操作
* 其他:代表有参数,将前三个删除,对参数部分单独处理
* */
switch (count($path)){
case 0:
$this->pathinfo=$this->route;
break;
case 1:
$this->pathinfo['module']=$path[0];
break;
case 2:
$this->pathinfo['module']=$path[0];
$this->pathinfo['controller']=$path[1];
break;
case 3:
$this->pathinfo['module']=$path[0];
$this->pathinfo['controller']=$path[1];
$this->pathinfo['action']=$path[2];
break;
default:
/*
* 处理参数,先获取参数部分存在$path
* 循环$path,匹配键值对
* 如果有键没值,则匹配失败,不存入参数
* */
$this->pathinfo['module']=$path[0];
$this->pathinfo['controller']=$path[1];
$this->pathinfo['action']=$path[2];
$path=array_slice($path,3);
for($i=0;$i<count($path);$i+=2){
if(isset($path[$i+1])){
$this->params[$path[$i]]=$path[$i+1];
}
}
break;
}
// echo '<pre>'.print_r($this->params,true).'</pre>';
// 返回route,方便以后链式访问
return $this;
}
public function dispatch()
{
$module=$this->pathinfo['module'];
$controller=$this->pathinfo['controller'];
$action=$this->pathinfo['action'];
$controller='app\\'.$module.'\controller\\'.ucfirst($controller);
// echo $controller;
// 没有这行代码时,路径出错也会返回到首页,所以删除
// if(!method_exists($controller,$action)){
// $action=$this->action;
// header('Location:/');
// }
return call_user_func_array([new $controller,$action],$this->params);
}
}
$route=new Route($config['route']);
$path=$_SERVER['QUERY_STRING'];
$routes=$route->parse($path);
require __DIR__ . '/app/admin/controller/User.php';
echo $routes=$route->dispatch();
目录 app/admin/controller/User.php
namespace app\admin\controller;
class User
{
public function add()
{
return 'my name is '.$name.', I`m '.$age;
}
}
访问 127.0.0.1/index.php?admin/user/add/name/php/age/4