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

相关文章

php基本函数汇总

1.统计数组元素个数 $arr = array( '1011,1003,1008,1001,1000,1004,1012', '1009', '1011,1003...

php简单统计中文个数的方法

本文实例讲述了php简单统计中文个数的方法。分享给大家供大家参考,具体如下: 之前的公司是做外贸的用到的都是英文所以统计的长度的时候是用strlen这个函数,一直也没有错误,但是现在统计...

php 验证码制作(网树注释思想)

1,生成随机数 用for循环确定生成几个随机数。 用随机函数生成范围内随机数。例如rand(1,15),生成1到15之间的数字。 用16位进制函数把生成数字字母化。dechex(rand...

简单谈谈PHP中的include、include_once、require以及require_once语句

1.include语句 使用include语句可以告诉PHP提取特定的文件,并载入它的全部内容 <?php inlude "fileinfo.php"; //此处添加...

PHP实现机器学习之朴素贝叶斯算法详解

本文实例讲述了PHP实现机器学习之朴素贝叶斯算法。分享给大家供大家参考,具体如下: 机器学习已经在我们的生活中变得随处可见了。比如从你在家的时候温控器开始工作到智能汽车以及我们口袋中的智...