Blogger Information
Blog 119
fans 3
comment 1
visits 94594
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
mvc pathinfo 路由的解析原理
赵大叔
Original
579 people have browsed it

mvc pathinfo 路由的解析原理

路由原理:从 url 地址中解析数据。

  • _GET: 返回查询字符串拆解的数组
  • implode(): 将数组切割成字符串
  • vprintf:按照指定模板打印
  • $_SERVER['QUERY_STRING'];获取 url 地址的查询字符串
  • $_SERVER['PATH_INFO'];获取地址的 PATHINFO 变量/ 路径变量
  • $_SERVER['REQUEST_URI'];获取相对于当前主机名下的文件的绝对路径

演示 PATHINFO 变量解析:

  1. <?php
  2. // 写一个简单的控制器
  3. class MyController
  4. {
  5. public function getInfor($name, $salary)
  6. {
  7. return "姓名: ==> $name, 工资: ==> $salary";
  8. }
  9. }
  10. // https://help10086.io/0222/demo1.php/MyController/getInfor/name/srp/salary/30000
  11. // var_dump($_SERVER['PATH_INFO']);
  12. // array_filter去除空字符 array_values将数组重新排序
  13. $res = array_values(array_filter(explode("/", $_SERVER['PATH_INFO'])));
  14. echo '<pre>';
  15. print_r($res);
  16. $controller = array_shift($res);
  17. // echo $controller;
  18. $method = array_shift($res);
  19. // echo $method;
  20. for ($i = 0; $i < count($res); $i += 2) {
  21. $params[$res[$i]] = $res[$i + 1];
  22. }
  23. echo '<pre>';
  24. print_r($params);
  25. // 第一种解决方法
  26. $infor = (new MyController)->getInfor($params['name'], $params['salary']);
  27. var_dump($infor);
  28. // 第二种回调的解决方法
  29. $infor = call_user_func_array([(new $controller), $method], [$params['name'], $params['salary']]);
  30. echo $infor;

解析 get 方式传参

  1. <?php
  2. // 写一个简单的控制器
  3. class MyController
  4. {
  5. public function getInfor($name, $salary)
  6. {
  7. return "姓名: ==> $name, 工资: ==> $salary";
  8. }
  9. }
  10. // var_dump($_SERVER['REQUEST_URI']);
  11. //获取到路由的地址
  12. $url = $_SERVER['REQUEST_URI'];
  13. //将路由地址转数组
  14. $urlarr = parse_url($url);
  15. // var_dump($urlarr['query']);
  16. //将需要的get部分的路由地址转数组
  17. parse_str($urlarr['query'], $xarr);
  18. // var_dump($xarr);
  19. // https://help10086.io/0222/demo2.php?name=srp&salary=30000
  20. echo (new MyController)->getInfor($xarr['name'], $xarr['salary']);

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