Blogger Information
Blog 33
fans 0
comment 0
visits 27350
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
服务端 - PHP - 路由
Original
753 people have browsed it

服务端 - PHP - 路由

一、概述

  • 目标:将URL中的控制器方法解析出来,映射到对应的控制器类和方法上

二、解析查询字符串

  1. // 1. 将控制器和方法拆分为数组
  2. $pathinfo = array_values(array_filter(explode('/', $_SERVER["PATH_INFO"])));
  3. // 2. 解析控制器
  4. $controller = ucfirst(array_shift($pathinfo));
  5. // 3. 解析方法
  6. $action = array_shift($pathinfo);
  7. // 4. 解析参数
  8. parse_str($_SERVER["QUERY_STRING"], $params);
  9. // 5. 调用控制器中的方法
  10. $obj = new $controller;
  11. echo $obj->$action(...array_values($params));

三、解析PATHINFO

  1. <?php
  2. class User {
  3. public function getName($id, $name) {
  4. return 'id:'.$id.'<br>'.'name:'.$name;
  5. }
  6. }
  7. // 1. 将控制器和方法拆分为数组
  8. $pathinfo = array_values(array_filter(explode('/', $_SERVER["PATH_INFO"])));
  9. // 2. 解析控制器
  10. $controller = ucfirst(array_shift($pathinfo));
  11. // 3. 解析方法
  12. $action = array_shift($pathinfo);
  13. echo $action;
  14. // 4. 解析参数:PATHINFO路径变量
  15. //用来保存从pathinfo解析出来的变量
  16. $params = [];
  17. //i+=2使当前索引横跨1个键值,跳到下一个键
  18. for ($i=0;$i<count($pathinfo);$i+=2) {
  19. //检查是否有键值
  20. if (isset($pathinfo[$i+1])) {
  21. //解析出新数组的键和值
  22. $params[$pathinfo[$i]] = $pathinfo[$i+1];
  23. }
  24. }
  25. // 5. 调用控制器中的方法
  26. $obj = new $controller;
  27. echo $obj->$action(...array_values($params));

四、课程总结

  • 今天学习了 PHP 的路由,通过上课认真听讲和认真完成老师布置的作业,使得我对 路由 的理解和运用更加深入和熟悉。最主要的知识点是明白和掌握了路由的原理以及路由解析的基本用法。
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!