加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

一个简单的php路由类

发布时间:2020-12-12 21:33:28 所属栏目:PHP教程 来源:网络整理
导读:本文实例为大家分享了php编写一个简单的路由类,供大家参考,具体内容如下 class Hcrail { /** callback function @var callable */ protected static $callback; /** match string or match regexp @var string */ protected static $match; protected stat

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

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;
    }

}

下载地址:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读