Correcting teacher:天蓬老师
Correction status:qualified
Teacher's comments:路由的形式非常多, 而且是http请求到达控制器的第一步, 是整个网站的哨兵
<?php
//创建控制器
class UserController
{
// 创建方法
public function getUser($id, $name)
{
// 直接返回数据
return "id ===> $id , name ===> $name";
}
}
//http://php11.edu/0514/index.php/控制器/方法/参数1/值1/参数2/值2/
//http://php11.edu/0514/index.php/user/getuser/id/200/name/admin
//1.先拿到$_SERVER['PATH_INFO']数据
//$pathinfo = $_SERVER['PATH_INFO'];
//echo $pathinfo; // 输出 /user/getuser/id/200/name/admin
//2.将字符串利用‘/’切割 转为数组
//$pathinfo = explode('/', $pathinfo);
//print_r($pathinfo);
//输出
//Array
//(
//[0] =>
//[1] => user
//[2] => getuser
//[3] => id
//[4] => 200
//[5] => name
//[6] => admin
//)
//3.将数组中的空值移除
//$pathinfo = array_filter($pathinfo);
//print_r($pathinfo);
//输出
//Array
//(
//[1] => user
//[2] => getuser
//[3] => id
//[4] => 200
//[5] => name
//[6] => admin
//)
// 4. 将数组键值进行重排
//$pathinfo = array_values($pathinfo);
//print_r($pathinfo);
//输出
//Array
//(
//[0] => user
//[1] => getuser
//[2] => id
//[3] => 200
//[4] => name
//[5] => admin
//)
### 将前几步组合到一起
$pathinfo = array_values(array_filter(explode('/',$_SERVER['PATH_INFO'])));
//print_r($pathinfo); // 输出值与第四步相同
//获取控制器 去除数组中的第一个值并进行首字母大写
$controller = ucfirst(array_shift($pathinfo)).'Controller';
//echo $controller; //输出 UserController
//获取方法 注意方法不区分大小写
$action = array_shift($pathinfo);
//echo $action; // 输出 getuser
//获取参数 当前数组中仅剩键值 使用for循环 获取
//print_r($pathinfo);
//输出
//Array
//(
//[0] => id
//[1] => 200
//[2] => name
//[3] => admin
//)
$params = [];
for ($i = 0 ; $i <= count($pathinfo) ; $i+=2){
// 判断如果当前键值对的下一个键值对存在则执行
if (isset($pathinfo[$i+1])){
$params[$pathinfo[$i]] = $pathinfo[$i+1];
}
}
//打印一下数组
//print_r($params);
//输出
//Array
//(
// [id] => 200
// [name] => admin
//)
//开始调用
//实例化控制器
$user = new $controller;
//调用方法并传值
echo $user->$action(...array_values($params));
//输出 id ===> 200 , name ===> admin
// 成功获取到值