一个简单的php路由类

yipeiwu_com5年前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程序设计有所帮助。

相关文章

thinkphp jquery实现图片上传和预览效果

thinkphp jquery实现图片上传和预览效果

先上效果图: 那个file按钮样式先忽略 点击选择图片(浏览),随便选一张图片 js代码如下 //上传图片立即预览 function PreviewImage(imgFil...

基于php中echo用逗号和用点号的区别详解

基于php中echo用逗号和用点号的区别详解

实例如下: <?php //点和逗号的测试,涉及到字符串的强制转换 echo 1+5; echo "<br /><br />"; echo '...

PHP错误Cannot use object of type stdClass as array in错误的解决办法

很多人在PHP输出一个二维数组的时候出现“Fatal error: Cannot use object of type stdClass as array in……”。解决办法分析如下:...

解析php中memcache的应用

所需环境:php 5.3.3apache 2.2.7mysql 5.5.8相关文档下载:点击下载解压Memcached_1.2.5文档,cmd下执行memcached.exe -d -i...

PHP生成条形码大揭秘

PHP生成条形码大揭秘

1.什么是条形码? 百度百科定义:条形码(barcode)是将宽度不等的多个黑条和空白,按照一定的编码规则排列,用以表达一组信息的图形标识符。常见的条形码是由反射率相差很大的黑条(简称条...