一个简单的php路由类

yipeiwu_com6年前PHP代码库

本文实例为大家分享了php编写一个简单的路由类,供大家参考,具体内容如下

<?php
namespace cmhc\Hcrail;
 
class Hcrail
{
 
  /**
   * callback function
   * @var callable
   */
  protected static $callback;
 
  /**
   * match string or match regexp
   * @var string
   */
  protected static $match;
 
  protected static $routeFound = false;
 
  /**
   * deal with get,post,head,put,delete,options,head
   * @param  $method
   * @param  $arguments
   * @return
   */
  public static function __callstatic($method, $arguments)
  {
    self::$match = str_replace("//", "/", dirname($_SERVER['PHP_SELF']) . '/' . $arguments[0]);
    self::$callback = $arguments[1];
    self::dispatch();
    return;
  }
 
  /**
   * processing ordinary route matches
   * @param string $requestUri
   * @return
   */
  public static function normalMatch($requestUri)
  {
    if (self::$match == $requestUri) {
      self::$routeFound = true;
      call_user_func(self::$callback);
    }
    return;
  }
 
  /**
   * processing regular route matches
   * @param string $requestUri
   * @return
   */
  public static function regexpMatch($requestUri)
  {
    //处理正则表达式
    $regexp = self::$match;
    preg_match("#$regexp#", $requestUri, $matches);
    if (!empty($matches)) {
      self::$routeFound = true;
      call_user_func(self::$callback, $matches);
    }
    return;
  }
 
  /**
   * dispatch route
   * @return
   */
  public static function dispatch()
  {
    if (self::$routeFound) {
      return ;
    }
    $requestUri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
    $requestMethod = $_SERVER['REQUEST_METHOD'];
 
    if (strpos(self::$match, '(') === false) {
      self::normalMatch($requestUri);
    } else {
      self::regexpMatch($requestUri);
    }
 
  }
 
  /**
   * Determining whether the route is found
   * @return boolean
   */
  public static function isNotFound()
  {
    return !self::$routeFound;
  }
 
}

下载地址:https://github.com/cmhc/Hcrail

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

相关文章

php ckeditor上传图片文件名乱码解决方法

打开editor/filemanager/connectors/php目录下commands.php,找到FileUpload函数,在复制代码 代码如下:$sExtension = su...

浏览器预览PHP文件时顶部出现空白影响布局分析原因及解决办法

在编写PHP文件过程中,发现在浏览器预览PHP文件时,顶部会出现一行空白,影响了页面的布局。 关于BOM header的解释如下: 通常情况下,使用Windows系统自带的记事本程序编写...

详解PHP序列化反序列化的方法

经常看到一些配置文件里面存放的是一些类似带有格式的变量名称和值,其实就是一个序列化的过程,在需要用到这些数据库的时候会进行一个反序列化过程,就是将这个字符串再还原成他原来的数据结构。下面...

深入解读php中关于抽象(abstract)类和抽象方法的问题分析

在面向对象(OOP)语言中,一个类可以有一个或多个子类,而每个类都有至少一个公有方法作为外部代码访问的接口。而抽象方法就是为了方便继承而引入的,现在来看一下抽象类和抽象方法分别是如何定义...

php输出金字塔的2种实现方法

本文实例讲述了php输出金字塔的2种实现方法。分享给大家供大家参考。具体分析如下: 下面给大家总结了两种实现金字塔打印的方法,一种是利用了自定义函数,另一种是利用了for循环了,其实两都...