博主信息
博文 17
粉丝 1
评论 0
访问量 23871
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
PHP路由与解析控制器
大A
原创
1118人浏览过

介绍

用地址调用指定类内的方法并传入参数

代码

  1. <?php
  2. //路由类
  3. class Routing
  4. {
  5. private $query, $path_array, $class, $method;
  6. public function __construct($server)
  7. {
  8. $this->query = $server['QUERY_STRING'];
  9. $path = $server['PATH_INFO'];
  10. $path = array_filter(explode('/', $path));
  11. $this->class = array_shift($path);
  12. $this->method = array_shift($path);
  13. $this->path_array=$path;
  14. }
  15. public function getquert()
  16. {
  17. parse_str($this->query, $result);
  18. return $result;
  19. }
  20. public function getclass()
  21. {
  22. return $this->class;
  23. }
  24. public function getmethod()
  25. {
  26. return $this->method;
  27. }
  28. public function getpath()
  29. {
  30. for ($i = 0; $i < count($this->path_array); $i += 2) {
  31. $value = $this->path_array[$i + 1];
  32. if ($value) $result[$this->path_array[$i]] = $value;
  33. }
  34. return $result;
  35. }
  36. }
  37. //控制器
  38. class Controller
  39. {
  40. public function show($array)
  41. {
  42. foreach ($array as $key => $value) {
  43. $result.=$key.'=>'.$value.'<br>';
  44. }
  45. return $result;
  46. }
  47. }
  48. //创建路由对象
  49. $a = new Routing($_SERVER);
  50. //解析调用的类
  51. $class=$a->getclass();
  52. ///解析调用的方法
  53. $method=$a->getmethod();
  54. ///解析方法内的参数
  55. $path=$a->getpath();
  56. //生成解析的类
  57. $b=new $class;
  58. //调用类内的方法
  59. echo $b->$method($path);
  60. //http://php.edu/index.php/Controller/show/ffff/5435/vcd/356/fds/5455
批改老师:天蓬老师天蓬老师

批改状态:合格

老师批语:将路由参数解析出来的方式许多, 我只提供了一种, 你还可以用其它方式, 还有参数的解析, 这个玩意比方法难
本博文版权归博主所有,转载请注明地址!如有侵权、违法,请联系admin@php.cn举报处理!
全部评论 文明上网理性发言,请遵守新闻评论服务协议
0条评论
作者最新博文
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号

  • 登录PHP中文网,和优秀的人一起学习!
    全站2000+教程免费学