一个简单的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跨时区(UTC时间)应用解决方案

1.将程序内部时区设置为UTC时间.(UTC 也可以叫 GMT) PHP设置: date_default_timezone_set("UTC"); Yii设置: config/main....

PHP面向对象多态性实现方法简单示例

本文实例讲述了PHP面向对象多态实现方法。分享给大家供大家参考,具体如下: 多态:父类引用指向子类对象(面向对象中能够根据使用类的上下文(使用输入不同的类调用不同类的方法)来重新定义或改...

PHP实现支持SSL连接的SMTP邮件发送类

本文实例讲述了PHP实现支持SSL连接的SMTP邮件发送类。分享给大家供大家参考。具体如下: 该实例代码测试过了gmail和QQ邮箱的SMTP。具体代码如下: 复制代码 代码如下:<...

PHP基于openssl实现的非对称加密操作示例

本文实例讲述了PHP基于openssl实现的非对称加密操作。分享给大家供大家参考,具体如下: 使用非对称加密主要是借助openssl的公钥和私钥,用公钥加密私钥解密,或者私钥加密公钥解密...

PHP面向对象自动加载机制原理与用法分析

PHP面向对象自动加载机制原理与用法分析

本文实例讲述了PHP面向对象自动加载机制原理与用法。分享给大家供大家参考,具体如下: 在学习PHP的面向对象的时候,会知道很多“语法糖”,也就是魔术方法。有一个加自动加载的魔术方法,叫:...