Blogger Information
Blog 17
fans 1
comment 0
visits 19902
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
PHP路由与解析控制器
大A
Original
936 people have browsed it

介绍

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

代码

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