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

yipeiwu_com6年前PHP代码库

本文实例讲述了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类自动装载、链式操作、魔术方法实现代码

1、自动装载实例 目录下有3个文件:index.php load.php tests文件夹 tests文件夹里有 test1.php <?php namespace T...

PHP用SAX解析XML的实现代码与问题分析

复制代码 代码如下: <?php $g_books = array(); $g_elem = null; function startElement( $parser, $name...

PHP中define() 与 const定义常量的区别详解

本文实例讲述了PHP中define() 与 const定义常量的区别。分享给大家供大家参考,具体如下: 前言 今天在Stackoverflow又看到一个很有趣的文章,所以翻译过后摘了过来...

PHP Document 代码注释规范

1. 什么是phpDocumentor ? PHPDocumentor 是一个用PHP写的工具,对于有规范注释的php程序,它能够快速生成具有相互参照,索引等功能的API文档。老的版本是...

php抽奖概率算法(刮刮卡,大转盘)

本文实例为大家分享了php中奖概率算法,可用于刮刮卡,大转盘等抽奖算法,用法很简单,代码里有详细注释说明,供大家参考,具体内容如下 <?php /* * 经典的概率算...