Blogger Information
Blog 30
fans 1
comment 0
visits 16062
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
mvc架构中 pathinfo路由的解析原理
moon
Original
460 people have browsed it

MVC架构中的路由解析原理

  • 1.当服务器接收到一个url请求时,服务器会获得一个超全局数组$_SERVER,记录url请求的各种信息,例如当服务器收到类似http://moon.io/0222/api/moon.php/user/index/id/1/name/moon这种url请求时,通过var_dump($_SERVER)可获得如下图数据

pathinfo

通过解析pathinfo信息,达到访问,moon.php中的index方法,代码如下

  1. <?php
  2. namespace mvc;
  3. class User
  4. {
  5. function index($id, $name)
  6. {
  7. return "您好$name,您的id是$id";
  8. }
  9. }
  10. $pathinfo = array_values(array_filter(explode("/", $_SERVER['PATH_INFO'])));
  11. $controller = __NAMESPACE__ . '\\' . array_shift($pathinfo);
  12. $method = array_shift($pathinfo);
  13. for ($i = 0; $i < count($pathinfo); $i += 2) {
  14. $params[$pathinfo[$i]] = $pathinfo[$i + 1];
  15. }
  16. echo call_user_func_array([(new $controller), $method], $params);

上述代码执行结果如下:

结果1

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