Blogger Information
Blog 32
fans 0
comment 0
visits 27961
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
PHP 简单路由实现
Yang_Sir
Original
2700 people have browsed it
  • 有命名空间的时候,自动加载要注意命名空间的路径问题
  • 访问的参数,参数名或者是顺序,一定要与后台一致

1.路由类

  • 客户端通过路径参数访问指定的控制器和方法
  • 后台从$_SERVER[‘PATH_INFO’]中获取路径参数
  1. <?php
  2. namespace home\route;
  3. class Route
  4. {
  5. public $controller = '';
  6. public $method = '';
  7. public $param =[];
  8. public function __construct()
  9. {
  10. $pathinfo = array_filter(explode('/',$_SERVER['PATH_INFO']));
  11. //取得控制器名
  12. $this->controller = ucfirst(array_shift($pathinfo));
  13. //取得方法名
  14. $this->method = array_shift($pathinfo);
  15. //取得参数
  16. for($i=0;$i<count($pathinfo);$i+=2){
  17. if(isset($pathinfo[$i+1]))
  18. $this->param[$pathinfo[$i]] = $pathinfo[$i+1];
  19. }
  20. }
  21. }

2.首页和自动加载

  • 首页通过自动加载实例化路由类,获取控制器、方法及方法的参数
  • 然后实例化控制器,调用指定方法

index.php

  1. <?php
  2. namespace home\route;
  3. require 'autoload.php';
  4. $route = new Route;//路由类
  5. $controller = __NAMESPACE__.'\\'.$route->controller;//添加命名空间
  6. $method = $route->method;
  7. $param = $route->param;
  8. extract($param);
  9. (new $controller)->$method($name,$rule);//访问控制器中的方法
  • 自动加载类文件
  • 由于传过来的类带有命名空间路径,需要特殊处理下

autoload.php

  1. namespace home\route;
  2. spl_autoload_register( function ($class){
  3. $file = $class.'.php';
  4. if(strpos($class,'\\')){
  5. //去掉命名空间。添加文件后缀
  6. $file = ltrim(strrchr($class,'\\'),'\\').'.php';
  7. }
  8. file_exists($file)? require $file:die($file.'不存在');
  9. });

3.演示效果

  • 创建一个Admin类,
  1. <?php
  2. namespace home\route;
  3. class Admin
  4. {
  5. //打印角色和名字
  6. public function hello($name,$rule){
  7. echo '欢迎您!'.$rule.'-'.$name;
  8. }
  9. }

通过以下路径参数访问
http://php11.edu/php/0514/route/index.php/admin/hello/name/admin/rule/管理员

结果,访问成功!

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