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;

}

}

希望本文所述对大家学习PHP程序设计有所帮助。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值