一步步编写PHP的Framework(十二)

雨伟大大_9046

雨伟大大_9046

2016-06-21

1609人浏览

原创

 

        我上次在讲redirect和forward的时候我就说过,这两个函数要正常使用还需要修改一下Route这个类,至少要将比如域名,控制器名,Action名等存储起来,后面调用redirect,forward的时候可以使用。

        现在我们就转到Route.php,原来这个类的代码很简单:

01

02 class Route extends Base {

03    public static function run() {

04       $controller= empty($_GET['c']) ? C('defaultController') : trim($_GET['c']); //设置了默认的控制器

05       $action = empty($_GET['a']) ? C('defaultAction') : trim($_GET['a']); //设置了默认的Action

06       $controllerBasePath = APP_PATH . '/UserApps/Modules/Controllers/';

07       $controllerFilePath = $controllerBasePath . $controller . 'Controller.php';

08       if(is_file($controllerFilePath)) {

09          include $controllerFilePath;

10          $controllerName = $controller . 'Controller';

11          if(class_exists($controllerName)) {

12             $controllerHandler = new $controllerName();

13             if(method_exists($controllerHandler,$action)) {

14                $controllerHandler->$action();

15             } else {

16                echo 'the method does not exists';

17             }

18          } else {

19             echo 'the class does not exists';

20          }

21       } else {

22          echo 'controller not exists';

23       }

24    }

25 }

 

        现在我们需要将域名取出来,那怎么弄呢?

        实际上PHP有一个强大的超全局变量$_SERVER,很多信息都存储在这里面,我们可以查看一下:

1

2 var_dump($_SERVER);

        我们注意到这里面有一个 HTTP_HOST属性,查看PHP手册,这么写的:

        Contents of the Host: header from the current request, if there is one. 

    假设现在有一个URL:http://localhost/test/test.php,那$_SERVER['HTTP_HOST']的值为什么呢,实际上为localhost。一般来说,我们想取到的是localhost/test,那么怎么获取后面的/test呢?

 

     我们继续搜索一下:

     发现REQUEST_URI,SCRIPT_FILENAME,SCRIPT_NAME,PHP_SELF的值都为/test/test.php,查询PHP手册解释分别为:

     1. The URI which was given in order to access this page; for instance, '/index.html'

     2. The absolute pathname of the currently executing script.

     3.Contains the current script's path. This is useful for pages which need to point to themselves. The __FILE__ constant contains the full path and filename of the current (i.e. included) file.

     4. The filename of the currently executing script, relative to the document root. For instance, $_SERVER['PHP_SELF'] in a script at the address http://example.com/test.php/foo.bar would be /test.php/foo.bar. The __FILE__ constant contains the full path and filename of the current (i.e. included) file. If PHP is running as a command-line processor this variable contains the script name since PHP 4.3.0. Previously it was not available.

 

       我们发现REQUEST_URI比较靠谱,当然,我这个地方测试的是apache的情况,nginx,iis等还有在.htaccess文件设置了rewrite规则后又不一样,如果真要写一个好的Route,考虑的东西会非常多的,针对于URL的普通模式,PATHINFO模式,REWRITE模式,兼容模式,我们使用最普通的方式。

       首先我们定义一个存储路径的类,Path.php:

01

02 class Path extends Base {

03    private static $_base = '';

04    private static $_controller = '';

05    private static $_action = '';

06    public static function setBasePath($base) {

07       self::$_base = $base;

08    }

09    public static function setController($controller) {

10       self::$_controller = $controller;

11    }

12    public static function setAction($action) {

13       self::$_action = $action;

14    }

15    public static function getBasePath() {

16       return self::$_base;

17    }

18    public static function getController() {

19       return self::$_controller;

20    }

21    public static function getAction() {

22       return self::$_action;

23    }

24 }

        就像Java中pojo,这个类只有setter和getter,我就不多讲了。

        然后再看看Route.php,首先还是获取URL,怎么获取呢?

1 $_SERVER['HTTP_HOST'] . substr($_SERVER['REQUEST_URI'],0,strrpos($_SERVER['REQUEST_URI'],'/'))

        由于之前已经讲了HTTP_HOST和REQUEST_URI的作用了,这段代码主要就说一下后面的substr和strrpos,substr就是截断字符串,strrpos是获取某一个子字符串在父字符串中最后一次出现的位置。

        PS:我这样写得还是有问题的,但是为了简便,不弄复杂了。

       然后就是将这些值存储到Path中,

1 Path::setBasePath($_SERVER['HTTP_HOST'] . substr($_SERVER['REQUEST_URI'],0,strrpos($_SERVER['REQUEST_URI'],'/')));

2       Path::setController($controller);

3       Path::setAction($action);

       设置了这些参数之后,在Controller.php中的redirect和forward的代码也要稍做修改:

01

02 class Controller extends Base {

03    protected function _redirect(Array $arr) {

04       array_key_exists('controller',$arr)  $arr['controller'] = Path::getContrller();

05       array_key_exists('action',$arr)  $arr['action'] = Path::getAction();;

06       $str = 'http://' . Path::getBasePath() . '/index.php?';

07       foreach($arr as $key => $val) {

08          if(!is_int($key)) {

09             $str .= ($key . '=' . $val . '&');

10          }

11       }

12       $str = substr($str,0,strlen($str) - 1);

13       Response::redirect($str);

14    }

15    protected function _forward(Array $arr) {

16       $controller = Path::getController();

17       $action = Path::getAction();

18       if(array_key_exists('controller',$arr)) {

19          $controller = $arr['controller'];

20       }

21       if(array_key_exists('action',$arr)) {

22          $action = $arr['action'];

23       }

24       $controller .= 'Controller';

25       if($controller === get_class()) {

26          if(method_exists($this,$action)) {

27             $this->$action();

28          } else {

29             //时间有限,不写逻辑了

30          }

31       } else {

32          if(class_exists($controller)) {

33             $class = new $controller();

34             if(method_exists($class,$action)) {

35                $class->$action();

36             } else {

37                //时间有限,不写了

38             }

39          } else {

40             //时间有限,不写了

41          }

42       }

43    }

44    protected  function _assign(Array $arr) {

45       View::assign($arr);

46    }

47    protected function _display($str) {

48       if(is_string($str)) {

49          $str = str_replace(array(

50             '.','#'

51          ),array(

52             '/','.'

53          ),$str);

54          View::display(MODULES_PATH . View::VIEW_BASE_PATH . $str . '.php');

55       }

56    }

57 }

       这个里面主要的改动就是控制器和Action的获取变成了调用Path类的方法,还有_redirect中,$str = 'http://' . Path::getBasePath() . '/index.php?',这里我假设使用的时http协议,并且不存在rewrite,服务器采用的是apache。

       搞定之后再使用_redirect和_forward,发现是不是没有问题了?



php免费学习视频:立即使用
踏上前端学习之旅,开启通往精通之路!从前端基础到项目实战,循序渐进,一步一个脚印,迈向巅峰!

相关文章

PHP速学教程(入门到精通)
PHP速学教程(入门到精通)

PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载

相关标签:

本站声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

相关专题

更多
Go-Zero API开发使用教程
Go-Zero API开发使用教程

本专题聚焦Go-Zero的API开发,拆解.api描述文件的语法结构、路由与分组定义、参数绑定与校验规则,说明统一响应体、JWT鉴权、跨域与接口文档生成的落地方式,并给出网关聚合与接口测试的实践建议。

2026.11.12

120

15

Go-Zero安装与goctl环境配置教程
Go-Zero安装与goctl环境配置教程

本专题围绕Go-Zero的安装与工具链配置展开,讲清Go版本要求、goctl安装方式、代理镜像、protoc依赖与环境变量设置,说明多版本共存、升级回退与CI流水线安装的做法,并整理安装阶段的常见报错与验证步骤。

2026.11.12

100

15

Go-Zero零基础入门教程
Go-Zero零基础入门教程

本专题整理Go-Zero的入门知识,从框架定位、环境准备到跑通第一个API服务,讲清目录分层、配置加载、日志与中间件的基本用法,并对比Gin、Kratos的差异,帮助Go开发者建立整体认知,判断它是否适合当前项目。

2026.11.12

60

15

Postman身份认证怎么配置
Postman身份认证怎么配置

本专题从实际API接口调试场景出发,讲解Postman身份认证的完整配置流程,包括常见认证协议介绍、授权参数设置、访问令牌填写、OAuth 2.0授权及认证失败排查,帮助用户正确完成接口授权与访问验证。

2026.11.06

160

12

Postman请求头Headers怎么设置
Postman请求头Headers怎么设置

围绕Postman HTTP请求头配置展开,讲解Headers选项的具体使用方式,包括Key和Value参数填写、请求头信息添加、常见Header字段设置及请求头修改方法,帮助用户解决接口调试过程中遇到的请求头配置问题。

2026.11.06

140

13

Postman接口请求发送教程
Postman接口请求发送教程

详细介绍Postman接口请求的创建与发送方法,涵盖GET和POST请求、URL配置、请求参数、Headers请求头、Body请求体设置以及响应结果查看,帮助用户掌握Postman接口请求的完整操作流程。

2026.11.06

120

10

DBeaver怎么导入数据
DBeaver怎么导入数据

DBeaver数据导入专题,整理Excel、CSV、SQL、TXT等常见文件的数据导入方法,涵盖目标数据库选择、数据表创建、字段映射、数据类型设置及导入参数配置等操作,帮助用户将本地文件中的数据写入数据库,并了解批量导入、重复数据处理和导入失败等常见问题的解决方法。

2026.11.05

100

12

DBeaver安全防护教程大全
DBeaver安全防护教程大全

DBeaver安全防护专题,围绕数据库连接安全、账号密码保护和访问权限管理展开,整理SSL/TLS加密连接、SSH隧道、数据库凭据保存及证书验证等配置方法,同时介绍敏感信息保护、远程连接风险和高权限账号使用等注意事项,帮助用户提高数据库日常管理的安全性。

2026.11.05

100

12

DBeaver连接创建与配置教程
DBeaver连接创建与配置教程

本专题聚焦DBeaver数据库连接配置与管理,覆盖从新建连接、选择数据库类型到填写连接参数和验证连接的完整流程。针对MySQL、PostgreSQL、SQL Server等常见数据库,整理相应的连接设置方法,并提供驱动缺失、认证失败和连接异常等问题的排查方向。

2026.11.04

100

16

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
Web Forms  教程
Web Forms 教程

共19课时 | 8.1万人学习

Web Pages 教程
Web Pages 教程

共64课时 | 45.2万人学习

ASP.NET 教程
ASP.NET 教程

共78课时 | 80.1万人学习