Correcting teacher:PHPz
Correction status:qualified
Teacher's comments:
从 url 中解析出控制器和方法,参数
1.get 请求,从查询字符串中解析
<?php
namespace phpcn;
class IndexController
{
public function index()
{
return '<h3>Hello world</h3>';
}
}
class UserController extends IndexController
{
public function hello($id = 1, $name = '张三')
{
return "<h3>ID$id:$name</h3>";
}
}
//1.$_GET[]
//router1.php?c=user&a=hello&id=12&name=peter
$c = $_GET['c'] ?? 'index';
$a = $_GET['a'] ?? 'index';
$id = $_GET['id'] ?? '1';
$name = $_GET['name'] ?? '张三';
//控制器名称
$class = __NAMESPACE__ . '\\' . ucfirst($c) . 'Controller';
//调用
echo ((new $class(null, null))->$a($id, $name));
//2.$_SERVER['QUERY_STRING']
if (@$_SERVER['QUERY_STRING']) {
//将字符串转为数组
parse_str($_SERVER['QUERY_STRING'], $params);
//去除空项
$params = array_filter($params);
// 结构数组
extract($params);
}
$c = $c ?? 'index';
$a = $a ?? 'index';
$id = $id ?? '1';
$name = $name ?? '张三';
//控制器名称
$class = __NAMESPACE__ . '\\' . ucfirst($c) . 'Controller';
//调用
echo ((new $class(null, null))->$a($id, $name));
2.主流路由解决方案: pathinfo
<?php
namespace phpcn;
//pathinfo
//router2.php/admin/user/hello/id/1/name/admin
//单入口/模块/控制器/方法
// 多入口
// 前台: index.php 做为入口 不需要模块, controller/action
// 后台: admin.php 做为入口, 不需要模块, controller/action
require __DIR__ . '/admin.php';
if (@$_SERVER['PATH_INFO']) {
//字符串转换为数组
$request = explode('/', trim(@$_SERVER['PATH_INFO'], '/'));
//解构
[$module, $controller, $action] = $request;
//取元素
$params = array_splice($request, 3);
//分割为数组块
$arr = array_chunk($params, 2);
//生成参数数组
$result = [];
foreach ($arr as $item) {
[$key, $value] = $item;
$result[$key] = $value;
}
extract($result);
}
$class = $module . '\\' . ucfirst($controller) . 'Controller';
echo ((new $class(null, null))->$action($id, $name));