一个简单的php路由类
程序员文章站
2024-04-02 13:38:52
本文实例为大家分享了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 闭包详解及实例代码