PHP simple pseudo-static URL mechanism implementation
曾几何时,我们公司准备开发一套新的建站系统,决定将以前的框架给KO掉,重新开发一套新的框架来适应新的系统功能。领导们不希望使用外面已有的框架,号称要开发有自己特色的框架(不懂开发的领导害死人)。于是我们又投入到了新的开发当中。
由于我们的系统支持伪静态,以前的系统是直接使用服务器apache或IIS自带的rewrite文件定义规则,而框架中没有任何路由机制,于是这次框架准备使用新的策略,由PHP实现路由机制。于是我开始了功能实现的探索之路。
开发之前,我先了解‘路由机制’要做什么,它主要做两件事。
1.路由机制就是把某一个特定形式的URL结构中提炼出来系统对应的参数。举个例子,如:http://main.wopop.com/article/1 其中:/article/1 -> ?_m=article&id=1。
2.其次,是将拥有对应参数的URL转换成特定形式的URL结构,是上面的过程的逆向过程。由于路由机制隔离了URL结构和参数的转换关系,使的日后结构的变化不会影响下面代码的执行。
通过上面的了解,可以得出要编写一个路由机制要一下几步:
1.编写服务器apache或IIS自带的rewrite文件,将URL结构导入index.php。
2.一个路由规则配置文件。
3.一个路由解析器,用来解析规则,匹配和转换URL。
于是,我们一一实现其中的每一个部分。
1.rewrite文件编写,以Apache为例:
<IfModule mod_rewrite.c> RewriteEngine On RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule (.+) index.php/$1 [L] </IfModule>
上面的代码就是将URL结构导入index.php中,具体的rewrite细节就不赘述了。
2.在PHP中设置一个路由规则配置文件routes.php,我简单的使用了一个hash数组编写规则:
/** *路由配置文件编写说明: * 路由配置在一个array数组中,一条记录代表一个规则 * 其中数组key的数据代表匹配的路径格式:使用特定的字符串标识 如:'/{id}' * 字符串中可以包含特定的变量,所有变量使用大括号{}包裹起来 * 数组value里是一个array数组,是对key中路径中变量进行特定处理 * 变量写在数组的key中,规范写在数组的value里,如:array('id'=>'/\d+/','_m'=>'frontpage','_a'=>'index') * 规范分成两类: * 1.格式判断:比如 '/{id}'=> array('id'=>'/\d+/','_m'=>'frontpage','_a'=>'index') 为例,其中'id'=>'/\d+/'就是一个格式判断, * 表示id变量只能是数字,格式判断后面只能使用正则表达式,由于PHP没有正则类,所以我指定 '/XXX/'和'#XXX#'格式的字符串为正则表达式 * 2.默认参数:比如 '/{id}'=> array('id'=>'/\d+/','_m'=>'frontpage','_a'=>'index') 为例,其中'_m'=>'frontpage'就是一个默认参数, * 因为前面的路径没有_m和_a信息,所以后面会使用默认参数作为_m和_a的值 * * 所以对于规则'/{id}'=> array('id'=>'/\d+/','_m'=>'frontpage','_a'=>'index')。我传入 /3 系统会转换成 index.php?_m=frontpage&_a=index&id=3 * * 规则匹配是按照$routes数组的顺序逐一匹配,一旦匹配上了就不往下匹配了。所以一些特定的匹配规则要放在前面,通用的放在后面。 * 否则可能导致不执行特定的匹配规则了 */ $routes= array( '/' => array('_m'=>'wp_frontpage','_a'=>'index'), '/{id}'=> array('id'=>'/\d+/','_m'=>'wp_frontpage','_a'=>'index'), '/{_m}/{_a}/{id}'=> array('id'=>'/\d+/'), '/{_m}/{_a}'=> array() );
3.路由机制中最复杂也是最重要的一部分,就是解析器。
解析器有两个类组成(名字可能起的不佳)。
一个是Route,作为整个解析器对外的接口,用于解析规则,匹配和转换URL,然而它只是一个代理,实际操作不是直接由它直接做的。
一个是RoutePattern,每个RoutePattern实例对应规则数组中的一条记录,一个Route实例包含多个RoutePattern,而Route中的所有操作都会调用内部所有RoutePattern实例操作,并进行整合。
class Route { private static $instance = null; private $routepatterns=array(); private function __construct() { $routes = array(); include ROOT."/routes.php"; foreach($routes as $key=>$value){ $this->routepatterns[]=new RoutePattern($key,$value); } if(!isset($_SERVER['PATH_INFO'])) return false; $urlpath= $_SERVER['PATH_INFO']; $ismatch=$this->match_url($urlpath); $strip_urlpath=str_replace('/','',$urlpath); if(!$ismatch&&!empty($strip_urlpath)){ Content::redirect(PAGE_404); } } /** * 用路由规则匹配对应的url地址,匹配成功将对应url参数放入$_GET中 * @param string url地址 * @return bool 是否匹配成功 */ public function match_url($urlpath){ foreach($this->routepatterns as $router){ $urlargs=$router->match_url($urlpath); if($urlargs!==false){ $_GET=array_merge($urlargs,$_GET); return true; } } return false; } public function rewrite_url($urlparams){ foreach($this->routepatterns as $router){ $urlstr=$router->rewrite_url($urlparams); if($urlstr!==false){ return $urlstr; } } $actualparams=array(); foreach($urlparams as $arg=>$val){ $actualparams[]=$arg."=".urlencode($val); } $actualparamstr=implode('&', $actualparams); $rewriteurl="/index.php"; if(!empty($rewriteurl))$rewriteurl.="?{$actualparamstr}"; return $rewriteurl; } public static function init() { if (null == self::$instance) { self::$instance = new Route(); } return self::$instance; } } class RoutePattern{ //...... }

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.
