abstract://config.php<?php return ['app'=>['debug'=>true],//默認(rèn)配置模塊、控制器、方法 'route'=>['module'=>'admin','controller'=>'index','acti
//config.php
<?php
return [
'app'=>['debug'=>true],
//默認(rèn)配置模塊、控制器、方法
'route'=>['module'=>'admin','controller'=>'index','action'=>'index']
];
// admin\controller\index.php
<?php
namespace admin\controller;
class Index{
public function Index($name='alice'){
return "my name is {$name}.";
}
}
//route.php
<?php
class Route{
//路由配置參數(shù)
protected $route=[];
//Url
protected $pathinfo=[];
//參數(shù)
protected $params=[];
public function __construct($route){
//加載配置信息
$this->route = $route;
}
// 獲取配置信息
public function getVar(){
return $this->route;
}
//url參數(shù)解析
public function parse($qstr){
//url轉(zhuǎn)為數(shù)組
$arr = explode('/',trim($qstr,'/'));
$arr = array_filter($arr);
switch(count($arr)){
case 0 :
$this->pathinfo = $this->route;
break;
case 1 :
$this->pathinfo['module'] = $arr[0];
$this->pathinfo['controller'] = $this->route['controller'];
$this->pathinfo['action'] = $this->route['action'];
break;
case 2 :
$this->pathinfo['module'] = $arr[0];
$this->pathinfo['controller'] = $arr[1];
$this->pathinfo['action'] = $this->route['action'];
break;
case 3 :
$this->pathinfo['module'] = $arr[0];
$this->pathinfo['controller'] = $arr[1];
$this->pathinfo['action'] = $arr[2];
break;
default :
$this->pathinfo['module'] = $arr[0];
$this->pathinfo['controller'] = $arr[1];
$this->pathinfo['action'] = $arr[2];
$paramVal = array_slice($arr,3);
for($i=0;$i<count($paramVal);$i+=2){
if(isset($paramVal[$i+1])){
$this->params[$paramVal[$i]] = $paramVal[$i+1];
}
}
break;
}
return $this->params;
}
public function dispatch(){
//獲取模塊名
$module = $this->pathinfo['module'];
//獲取控制器類
$controller = $module.'\\controller\\'.ucfirst($this->pathinfo['controller']);
//獲取方法名
$action = $this->pathinfo['action'];
//判斷類中是否上輩子在此方法
if(!method_exists($controller,$action)){
echo '不存在此方法!';
}
//調(diào)用call_user_func_array
return call_user_func_array([new $controller,$action],$this->params);
}
}
//加載默認(rèn)配置
$route = (require 'config.php')['route'];
//聲明Route類實例
$route = new Route($route);
//獲取url參數(shù)
$qstr = $_SERVER['QUERY_STRING'];
//echo '<pre>'.var_export($route->getVar(),true).'<br>';
//echo $qstr;
//參數(shù)路由解析
$route->parse($qstr);
//echo '<pre>'.var_export($arr,true).'<br>';
//加載類文件
require __DIR__.'/admin/controller/Index.php';
//請求分發(fā)
echo $route->dispatch();
Correcting teacher:查無此人Correction time:2019-10-12 16:28:07
Teacher's summary:完成的不錯。自己寫路由,可以更好的了解路由機制。繼續(xù)加油