Blogger Information
Blog 33
fans 0
comment 0
visits 17089
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
路由原理与实现
lucaslwk
Original
475 people have browsed it

路由原理与实现

路由原理

从 url 中解析出控制器和方法,参数

路由实现

1.get 请求,从查询字符串中解析

  1. <?php
  2. namespace phpcn;
  3. class IndexController
  4. {
  5. public function index()
  6. {
  7. return '<h3>Hello world</h3>';
  8. }
  9. }
  10. class UserController extends IndexController
  11. {
  12. public function hello($id = 1, $name = '张三')
  13. {
  14. return "<h3>ID$id:$name</h3>";
  15. }
  16. }
  17. //1.$_GET[]
  18. //router1.php?c=user&a=hello&id=12&name=peter
  19. $c = $_GET['c'] ?? 'index';
  20. $a = $_GET['a'] ?? 'index';
  21. $id = $_GET['id'] ?? '1';
  22. $name = $_GET['name'] ?? '张三';
  23. //控制器名称
  24. $class = __NAMESPACE__ . '\\' . ucfirst($c) . 'Controller';
  25. //调用
  26. echo ((new $class(null, null))->$a($id, $name));
  27. //2.$_SERVER['QUERY_STRING']
  28. if (@$_SERVER['QUERY_STRING']) {
  29. //将字符串转为数组
  30. parse_str($_SERVER['QUERY_STRING'], $params);
  31. //去除空项
  32. $params = array_filter($params);
  33. // 结构数组
  34. extract($params);
  35. }
  36. $c = $c ?? 'index';
  37. $a = $a ?? 'index';
  38. $id = $id ?? '1';
  39. $name = $name ?? '张三';
  40. //控制器名称
  41. $class = __NAMESPACE__ . '\\' . ucfirst($c) . 'Controller';
  42. //调用
  43. echo ((new $class(null, null))->$a($id, $name));

2.主流路由解决方案: pathinfo

  1. <?php
  2. namespace phpcn;
  3. //pathinfo
  4. //router2.php/admin/user/hello/id/1/name/admin
  5. //单入口/模块/控制器/方法
  6. // 多入口
  7. // 前台: index.php 做为入口 不需要模块, controller/action
  8. // 后台: admin.php 做为入口, 不需要模块, controller/action
  9. require __DIR__ . '/admin.php';
  10. if (@$_SERVER['PATH_INFO']) {
  11. //字符串转换为数组
  12. $request = explode('/', trim(@$_SERVER['PATH_INFO'], '/'));
  13. //解构
  14. [$module, $controller, $action] = $request;
  15. //取元素
  16. $params = array_splice($request, 3);
  17. //分割为数组块
  18. $arr = array_chunk($params, 2);
  19. //生成参数数组
  20. $result = [];
  21. foreach ($arr as $item) {
  22. [$key, $value] = $item;
  23. $result[$key] = $value;
  24. }
  25. extract($result);
  26. }
  27. $class = $module . '\\' . ucfirst($controller) . 'Controller';
  28. echo ((new $class(null, null))->$action($id, $name));
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