Blogger Information
Blog 31
fans 0
comment 0
visits 14180
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
用代码演绎mvc pathinfo路由的解析原理
木子木杉
Original
377 people have browsed it

用代码演绎mvc pathinfo路由

解析pathinfo,从url解析控制器和方法,参数
从谷歌搜索输入url
http://chloe.io/0222/demo.php/user/index/id/2/name/jim

  1. <?php
  2. //api mvc 这种架构模式 url地址都会映射到控制器下面的一个具体操作方法上
  3. namespace mvc;
  4. class User
  5. {
  6. function index($id, $name)
  7. {
  8. return "您好$name,您的Id是$id";
  9. }
  10. }
  11. // var_dump($_SERVER);
  12. var_dump($_SERVER['PATH_INFO']);
  13. var_dump(explode("/", $_SERVER['PATH_INFO'])); // /user/index/id/2/name/jim
  14. //先用explode分割成数组
  15. //用array_filte()去除空数组,用array_values()重新排数组键
  16. $pathinfo = array_values(array_filter(explode("/", $_SERVER['PATH_INFO'])));
  17. // var_dump($pathinfo);
  18. //用array_shift()取出第一个字符串与命名空间拼接,为控制器
  19. $controller = __NAMESPACE__ . '\\' . array_shift($pathinfo);
  20. var_dump($controller);
  21. // var_dump($pathinfo);
  22. //用array_shift()取出字符串为方法
  23. $method = array_shift($pathinfo);
  24. var_dump($method);
  25. // $params = ['id' => 1, 'name' => 'peter'];
  26. var_dump($pathinfo);
  27. //前提是参数是通过pathinfo方式提交过来
  28. for ($i = 0; $i < count($pathinfo); $i += 2) {
  29. $params[$pathinfo[$i]] = $pathinfo[$i + 1];
  30. }
  31. //取出参数数组
  32. var_dump($params);
  33. //用call_user_func_array()返回回调函数的结果
  34. echo call_user_func_array([(new $controller), $method], $params);
  35. //改变url的参数值,回调函数的值随之改变
Correcting teacher:PHPzPHPz

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