Blogger Information
Blog 48
fans 0
comment 0
visits 34174
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
实现一个简单的URL到控制器方法的映射(0805)
丶久而旧之丶
Original
659 people have browsed it

路由

  1. <?php
  2. namespace MVC;
  3. class UserController
  4. {
  5. public function show()
  6. {
  7. return 'PHP中文网';
  8. }
  9. public function show1($name, $course)
  10. {
  11. return '姓名:' . $name . ',课程:' . $course;
  12. }
  13. }
  14. // 先获取pathinfo信息
  15. // http://xiaoshang.com/PHP/0805/0805.php/user/show
  16. $pathinfo = explode('/', $_SERVER['PATH_INFO']);
  17. // 过滤掉空元素后键名重置
  18. $path = array_values(array_filter($pathinfo));
  19. // 生成控制器类名(有命名空间需要拼接命名空间)
  20. $controller = __NAMESPACE__ . '\\' . ucfirst(array_shift($path)) . 'Controller';
  21. $show = array_shift($path);
  22. // echo (new $controller)->$show();
  23. echo call_user_func([(new $controller), $show]), '<hr>';
  24. // 方法需要参数(方法参数还是用pathinfo获取)
  25. // http://xiaoshang.com/PHP/0805/0805.php/user/show/show1/name/admin/course/PHP/sex
  26. $show1 = array_shift($path);
  27. $arr = [];
  28. for ($i = 0; $i < count($path); $i += 2) {
  29. // 需要做判断不要出现空值
  30. if (isset($path[$i + 1]))
  31. $arr[$path[$i]] = $path[$i + 1];
  32. }
  33. echo call_user_func_array([(new $controller), $show1], $arr)
  34. // URL中的pathinfo参数不使用键名
  35. // http: //xiaoshang.com/PHP/0805/0805.php/user/show1/admin/PHP
  36. $controller = __NAMESPACE__ . '\\' . ucfirst(array_shift($path)) . 'Controller';
  37. $show1 = array_shift($path);
  38. echo call_user_func_array([(new $controller), $show1], $path);

URL中的pathinfo参数不使用键名

总结

1.了解了url怎么映射到控制方法上

Correcting teacher:天蓬老师天蓬老师

Correction status:qualified

Teacher's comments:理解了就好
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