当前位置:首页 > PHP教程 > PHP高级教程

一个简单的php路由类

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

<?php
namespace cmhchcrail;
 
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程序设计有所帮助。


【说明】本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:)!