Blogger Information
Blog 24
fans 0
comment 0
visits 18495
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
路由器解析
昔年
Original
861 people have browsed it

路由器解析

1.解析http://php11.edu/0514/route.php/user/getuser?id=100&name=admin这种类型路由

  1. <?php
  2. class UserController
  3. {
  4. public function getUser($id,$name){
  5. return "id===>$id,name===>$name";
  6. }
  7. }
  8. //1.解析出pathinfo
  9. $pathinfo = array_filter(explode('/',$_SERVER['PATH_INFO']));
  10. //2.解析控制器
  11. $controller = array_shift($pathinfo).'Controller';
  12. //3.解析控制器的方法
  13. $action = array_pop($pathinfo);
  14. //4.解析参数
  15. parse_str($_SERVER['QUERY_STRING'],$params);
  16. //5.调用控制器的的方法
  17. $user = new $controller;
  18. echo $user->$action(...array_values($params));

2.解析http://php11.edu/0514/route1.php/user/getuser/id/300/name/Admin/salary这种类型路由

  1. <?php
  2. class UserController
  3. {
  4. public function getUser($id,$name){
  5. return "我的id===>$id,我的name===>$name";
  6. }
  7. }
  8. //1.解析出pathinfo
  9. $pathinfo = array_filter(explode('/',$_SERVER['PATH_INFO']));
  10. //2.解析控制器
  11. $controller = array_shift($pathinfo).'Controller';
  12. //3.解析控制器的方法
  13. $action = array_shift($pathinfo);
  14. for($i = 0;$i<count($pathinfo);$i+=2){
  15. if(isset($pathinfo[$i+1])) $params[$pathinfo[$i]] = $pathinfo[$i+1];
  16. }
  17. //4.调用控制器中的方法
  18. $user = new $controller;
  19. echo $user->$action(...array_values($params));

总结:路由解析主要用到$_SERVER这个全局变量,通过PATH_INFO以及QUERY_STRING两个参数得到控制器方法以及传递的参数,对于后面一种全是通过’/‘的路由,在参数中需要进行判定其是否有相应的值。

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!