Correcting teacher:天蓬老师
Correction status:qualified
Teacher's comments:字符串函数用得很熟练
<?php
namespace home\route;
class Route
{
public $controller = '';
public $method = '';
public $param =[];
public function __construct()
{
$pathinfo = array_filter(explode('/',$_SERVER['PATH_INFO']));
//取得控制器名
$this->controller = ucfirst(array_shift($pathinfo));
//取得方法名
$this->method = array_shift($pathinfo);
//取得参数
for($i=0;$i<count($pathinfo);$i+=2){
if(isset($pathinfo[$i+1]))
$this->param[$pathinfo[$i]] = $pathinfo[$i+1];
}
}
}
index.php
<?php
namespace home\route;
require 'autoload.php';
$route = new Route;//路由类
$controller = __NAMESPACE__.'\\'.$route->controller;//添加命名空间
$method = $route->method;
$param = $route->param;
extract($param);
(new $controller)->$method($name,$rule);//访问控制器中的方法
autoload.php
namespace home\route;
spl_autoload_register( function ($class){
$file = $class.'.php';
if(strpos($class,'\\')){
//去掉命名空间。添加文件后缀
$file = ltrim(strrchr($class,'\\'),'\\').'.php';
}
file_exists($file)? require $file:die($file.'不存在');
});
<?php
namespace home\route;
class Admin
{
//打印角色和名字
public function hello($name,$rule){
echo '欢迎您!'.$rule.'-'.$name;
}
}
通过以下路径参数访问
http://php11.edu/php/0514/route/index.php/admin/hello/name/admin/rule/管理员
结果,访问成功!