php如何实现简单路由?本文主要为大家详细介绍了一个简单的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;
}
}相关推荐:
dmSOBC SHOP网店系统由北京时代胜腾信息技术有限公司(http://www.webzhan.com)历时6个月开发完成,本着简单实用的理念,商城在功能上摒弃了外在装饰的一些辅助功能,尽可能的精简各项模块开发,做到有用的才开发,网店V1.0.0版本开发完成后得到了很多用户的使用并获得了好评,公司立即对网店进行升级,其中包括修正客户提出的一些意见和建议,现对广大用户提供免费试用版本,如您在使用
0
立即学习“PHP免费学习笔记(深入)”;
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
C++高性能并发应用_C++如何开发性能关键应用
Java AI集成Deep Java Library_Java怎么集成AI模型部署
Golang后端API开发_Golang如何高效开发后端和API
Python异步并发改进_Python异步编程有哪些新改进
C++系统编程内存管理_C++系统编程怎么与Rust竞争内存安全
Java GraalVM原生镜像构建_Java怎么用GraalVM构建高效原生镜像
Python FastAPI异步API开发_Python怎么用FastAPI构建异步API
C++现代C++20/23/26特性_现代C++有哪些新标准特性如modules和coroutines
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号