一个简单的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伪静态写法附代码

比如这个网页 //www.jb51.net/soft.php/1,100,8630.html 其实处理的脚本是soft.php 参数为1,100,8630 相当于soft.ph...

PHP在字符断点处截断文字的实现代码

复制代码 代码如下: //所谓断字 (word break),即一个单词可在转行时断开的地方。这一函数将在断字处截断字符串。 // Please acknowledge use of t...

PHP使用正则表达式获取微博中的话题和对象名

本文实例讲述了PHP使用正则表达式获取微博中的话题和对象名的方法。分享给大家供大家参考。具体实现方法如下: $post_content = "@jb51和@twitter在研究用#P...

五款PHP代码重构工具推荐

五款PHP代码重构工具推荐

在软件工程学里,重构代码一词通常是指在不改变代码的外部行为情况下而修改源代码。软件重构需要借助工具完成,而重构工具能够修改代码同时修改所有引用该代码的地方。本文收集了五款出色的PHP代码...

PHP计数器的实现代码

复制代码 代码如下:<?php/*使用文本文件记录数据的简单实现*/$counter=1;if(file_exists("mycounter.txt")){$fp=fopen("m...