您的位置:首页 > 编程语言 > PHP开发

一个简单的php路由类

2016-05-29 00:00 302 查看
本文实例为大家分享了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程序设计有所帮助。

您可能感兴趣的文章:

Phpbean路由转发的php代码
php编写一个简单的路由类
PHP URL路由类实例
asp.net不用设置iis实现url重写 类似伪静态路由
thinkphp路由规则使用示例详解和伪静态功能实现(apache重写)
php处理restful请求的路由类分享
php url路由入门实例
thinkphp的URL路由规则与配置实例
ThinkPHP、ZF2、Yaf、Laravel框架路由大比拼
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  php 路由类