当前位置: 移动技术网 > IT编程>开发语言>PHP > 一个简单的php路由类

一个简单的php路由类

2017年12月12日  | 移动技术网IT编程  | 我要评论

治疗尖锐湿疣的中药方,北邮李伊娜,看猪成陛

本文实例为大家分享了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程序设计有所帮助。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网