一个简单的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关于foreach复制知识点总结

PHP的foreach是一个非常整洁和切中要害的语言结构。仍然有些人不喜欢使用它,因为他们认为它是缓慢的。一个通常命名的原因是foreach复制它迭代的数组。 因此,一些人建议写:...

PHP赋值的内部是如何跑的详解

PHP赋值的内部是如何跑的详解

前言 在PHP中,一个变量被赋值,内部到底经历了怎样的逻辑判断呢? PHP在内核中是通过zval这个结构体来存储变量的,它的定义在Zend/zend.h文件里 struct _zva...

php5.5使用PHPMailer-5.2发送邮件的完整步骤

前言 这几天一直被邮件发送功能搞得头大,作为一个小白,遇到坑总是难免的。今天终于把phpmailer搞定了,下面就来总结一下 PHPMailer - A full-featured em...

PHP实现动态获取函数参数的方法示例

本文实例讲述了PHP实现动态获取函数参数的方法。分享给大家供大家参考,具体如下: PHP 在用户自定义函数中支持可变数量的参数列表。其实很简单,只需使用 func_num_args()...

自定义php类(查找/修改)xml文档

近期在看PHP的教学视频,其中讲到了 PHP 操作 xml 文档,学了点儿 DOMDocument 类。自己查手册又全英文,看不大懂。但还是自己写了个类,实现了查找 xml 节点,并修改...