一个简单的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 启动报错如何解决

复制代码 代码如下: [root@abc lnmp]# service php-fpm start Starting php-fpm eAccelerator: Could not al...

php中jpgraph类库的使用介绍

用Jpgraph,只要了解它的一些内置函数,可以轻松得画出折线图、柱形图、饼状图等图表。 首先要保证PHP打开了Gd2的扩展: 打开PHP.ini,定位到extension=php_gd...

php使用curl出现Expect:100-continue解决方法

本文实例讲述了php使用curl出现Expect:100-continue解决方法。分享给大家供大家参考。具体如下: 使用curl POST数据时,如果POST的数据大于1024字节,c...

利用PHP扩展Xhprof分析项目性能实践教程

利用PHP扩展Xhprof分析项目性能实践教程

一、背景 项目即将上线,想通过一些工具来分析代码的稳定性和效率,想起在上个团队时使用过的xhprof扩展;因为换了新电脑,所以需要重新编译此扩展,现将安装与实际排查过程完整记录下来,方...

PHP中shuffle数组值随便排序函数用法

本文实例讲述了shuffle数组值随便排序函数的用法,分享给大家供大家参考。 具体实例代码如下: 复制代码 代码如下:$typename=20; $rtitle='tt'; for(...