Blogger Information
Blog 14
fans 0
comment 1
visits 12729
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
解析URL中的控制器、方法、参数
王珂
Original
1072 people have browsed it

解析URL中的控制器、方法、参数

参数为查询变量

  1. <?php
  2. // 路由原理
  3. // 目标:将URL中的控制器,方法解析出来,映射到对应的控制器类和方法上
  4. //解析--控制器、方法、参数(查询变量)
  5. // http://phpedu.io/0514/routen1.php/user/getuserid?id=19&name=admin
  6. // 控制器
  7. class UserController
  8. {
  9. public function getUser($id, $name)
  10. {
  11. return "id ==> $id, name ==> $name";
  12. }
  13. }
  14. // 1. 解析出PATHINFO,explode把字符串打散为数组,array_filter去空值,array_values返回数组的所有值(非键名)
  15. $pathinfo = array_values(array_filter(explode('/', $_SERVER['PATH_INFO'])));
  16. // 2. 解析控制器
  17. $controller = ucfirst($pathinfo[0]) . 'Controller';
  18. //$controller = ucfirst(array_shift($pathinfo)) . 'Controller';
  19. // 3. 解析控制器中的方法
  20. $action = $pathinfo[1];
  21. //$action = array_shift($pathinfo);
  22. // 4. 解析参数:将查询字符串存放到关联数组$params
  23. parse_str($_SERVER['QUERY_STRING'], $params);
  24. // 5. 调用控制器方法
  25. $user = new $controller();
  26. echo $user->$action(...array_values($params));

结果

id ==> 19, name ==> admin

参数为路径变量

  1. <?php
  2. // 路由原理
  3. // 目标:将URL中的控制器,方法解析出来,映射到对应的控制器类和方法上
  4. //解析--控制器、方法、参数(路径变量)
  5. // http://phpedu.io/0514/routen2.php/user/getuser/id/200/name/admin
  6. // 控制器
  7. class UserController
  8. {
  9. public function getUser($id, $name)
  10. {
  11. return "我的id ==> $id, 我的姓名 ==> $name";
  12. }
  13. }
  14. // 1. 解析出PATHINFO,explode把字符串打散为数组,array_filter去空值,array_values返回数组的所有值(非键名)
  15. $pathinfo = array_values(array_filter(explode('/', $_SERVER['PATH_INFO'])));
  16. // 2. 解析控制器
  17. $controller = ucfirst(array_shift($pathinfo)) . 'Controller';
  18. // 3. 解析控制器中的方法
  19. $action = array_shift($pathinfo);
  20. // 4. 解析参数: pathinfo路径变量
  21. // 这里放的是从pathinfo中解析出来的变量组成的数组
  22. $params = [];
  23. for ($i=0; $i<count($pathinfo); $i+=2) {
  24. // 检查当前pathinfo变量是否有值?
  25. if (isset($pathinfo[$i+1])){
  26. $params[$pathinfo[$i]] = $pathinfo[$i+1];
  27. }
  28. }
  29. // 5. 调用控制器方法
  30. $user = new $controller();
  31. echo $user->$action(...array_values($params));

结果

我的id ==> 200, 我的姓名 ==> admin

Correcting teacher:天蓬老师天蓬老师

Correction status:qualified

Teacher's comments:理解框架的运行原理就是从url到类方法的映射, 这个很重要, 这也是路由的基础
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!