一个简单的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程序设计有所帮助。

相关文章

Laravel 5.4重新登录实现跳转到登录前页面的原理和方法

前言 本文主要给大家介绍的是关于Laravel5.4重新登录跳转到登录前页面的相关内容,分享出来供大家参考学习,下面话不多说,来一起看看详细的介绍: 一、应用场景: 用户登陆后存在过...

php preg_match_all结合str_replace替换内容中所有img

采集回来的图片img标签中,有好多javascript脚本和无用的信息,必需过替换自己想要的,比如alt。先看看要过滤的内容,我随便复制出来: 复制代码 代码如下: sdfsdfsdf&...

javascript+php实现根据用户时区显示当地时间的方法

本文实例讲述了javascript+php实现根据用户时区显示当地时间的方法。分享给大家供大家参考。具体如下: 在跨时区应用中会用到下面代码,这是以前写的一段代码。 服务器保存相关时间配...

PHP求小于1000的所有水仙花数的代码

水仙花数是一个n(>=3)位数字的数, 它等于每个数字的n次幂之和. 例如, 153是一个水仙花数, 153=1³+5³+3³. 编写程序, 求解小于...

浅谈PHP无限极分类原理

浅谈PHP无限极分类原理

1.递归:程序调用自身的编程技巧称为递归 2.案例: /** * @param 递归 $[name] */ function deeploop(&$i=1){ echo...