华域联盟 PHP PHP从零开始打造自己的MVC框架之路由类实现方法分析

PHP从零开始打造自己的MVC框架之路由类实现方法分析

本文实例讲述了PHP从零开始打造自己的MVC框架之路由类实现方法。分享给大家供大家参考,具体如下:

core目录下,新建一个名为lib的子目录,然后把我们前面写个route.php这个文件移动到这个目录下。

因为route类文件路径修改,所以在实例化的时候:

new \core\lib\route();

然后我们来完善route.php:

<?php
namespace core\lib;
class Route
{
  public $controller; // 控制器
  public $action; // 方法(动作)
  public function __construct()
  {
    // xxx.com/index.php/index/index
    // xxx.com/index.php/index
    /*
     * 1.隐藏index.php
     * 2.获取URL 参数部分
     * 3.返回对应控制器和方法
     * */
    if(isset($_SERVER['REQUEST_URI']) && $_SERVER['REQUEST_URI'] != '/'){
      // 处理成这种格式:index/index
      $path = $_SERVER['REQUEST_URI'];
      $pathArr = explode('/',trim($path,'/'));
      if(isset($pathArr[0])){
        $this->controller = $pathArr[0];
      }
      unset($pathArr[0]);
      if(isset($pathArr[1])){
        $this->action = $pathArr[1];
        unset($pathArr[1]);
      }else{
        $this->action = 'index';
      }
      // url多余部分(参数部分)转换成 GET
      // id/1/str/2
      $count = count($pathArr) + 2;
      $i = 2;
      while($i < $count){
        if(isset($pathArr[$i + 1])){
          $_GET[$pathArr[$i]] == $pathArr[$i + 1];
        }
        $i = $i + 2;
      }
      p($_GET); // 打印GET
    }else{
      $this->controller = 'index'; // 默认控制器
      $this->action = 'index'; // 默认方法
    }
  }
}

更多关于PHP相关内容感兴趣的读者可查看本站专题:《php面向对象程序设计入门教程》、《PHP数组(Array)操作技巧大全》、《PHP基本语法入门教程》、《PHP运算与运算符用法总结》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总

希望本文所述对大家PHP程序设计有所帮助。

您可能感兴趣的文章:

本文由 华域联盟 原创撰写:华域联盟 » PHP从零开始打造自己的MVC框架之路由类实现方法分析

转载请保留出处和原文链接:https://www.cnhackhy.com/59000.htm

本文来自网络,不代表华域联盟立场,转载请注明出处。

作者: sterben

发表回复

联系我们

联系我们

2551209778

在线咨询: QQ交谈

邮箱: [email protected]

工作时间:周一至周五,9:00-17:30,节假日休息

关注微信
微信扫一扫关注我们

微信扫一扫关注我们

关注微博
返回顶部