php路由类 一个简单的php路由类

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

php路由类 一个简单的php路由类

imhuchao   2021-03-22 我要评论
想了解一个简单的php路由类的相关内容吗,imhuchao在本文为您仔细讲解php路由类的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点: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程序设计有所帮助。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们