本文实例讲述了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程序设计有所帮助。