PHP simple pseudo-static URL mechanism implementation

Source: Internet
Author: User
PHP simple pseudo-static URL mechanism implementation & nbsp; our company was prepared to develop a new website construction system and decided to drop the previous framework to KO, re-develop a new framework to adapt to new system functions. Leaders do not want to use the existing frameworks. They claim that they want to develop frameworks with their own characteristics (leaders who do not know how to develop them will be killed ). So we have invested in new development. & Nbsp; because our system supports pseudo-static, the previous PHP simple pseudo-static URL mechanism was implemented.
Once upon a while, our company was preparing to develop a new website construction system, deciding to drop the previous framework to KO, and re-developing a new framework to adapt to the new system functions. Leaders do not want to use the existing frameworks. They claim that they want to develop frameworks with their own characteristics (leaders who do not know how to develop them will be killed ). So we have invested in new development.
Because our system supports pseudo-static data, the previous system directly used the rewrite file definition rules provided by apache or IIS, but the framework does not have any routing mechanism, so this framework is ready to use a new policy, and PHP implements the routing mechanism. So I started to explore how to implement the function.
Before development, I should first understand what the 'routing mechanism 'is to do. it mainly does two things.
1. the routing mechanism is to extract the system parameters from a specific URL structure. For example: http://main.wopop.com/article/1 Where:/article/1->? _ M = article & id = 1.
2. Second, the URL with corresponding parameters is converted into a specific URL structure, which is the inverse process of the above process. Because the routing mechanism isolates the conversion relationship between URL structures and parameters, subsequent structure changes will not affect the execution of the following code.
Through the above understanding, we can conclude that it takes several steps to write a routing mechanism:
1. Compile the rewrite file on apache or IIS server, and import the URL structure to index. php.
2. a routing rule configuration file.
3. a route parser used to parse rules, match and convert URLs.
Therefore, we implement each part one by one.

1. write the rewrite file. take Apache as an example:
 
  RewriteEngine OnRewriteRule ^index\.php$ - [L]RewriteCond %{REQUEST_FILENAME} !-fRewriteCond %{REQUEST_FILENAME} !-dRewriteRule (.+) index.php/$1 [L]
 

The above code imports the URL structure into index. php. the detailed rewrite details will not be described in detail.

2. set a routing rule configuration file routes. PHP in php. I simply used a hash array to write the rule:
/*** Route configuration file description: * in an array, a record represents a rule * where the data of the array key represents the matching path format: use a specific string identifier such as '/{id}' * the string can contain specific variables. all variables are enclosed by braces {}. * The array value is an array, is specific to the variables in the path in the key * the variables are written in the key of the array and written in the value of the array in a standard format, such: array ('id' => '/\ d +/', '_ m' => 'frontpage',' _ A' => 'index ') * The specification is divided into two categories: * 1. format determination: for example, '/{id}' => array ('id' => '/\ d +/', '_ m' => 'frontpage ', '_ A' => 'index') for example, where 'id' =>'/\ d +/'is a format judgment, * indicates that the id variable can only be a number, only regular expressions can be used to determine the format. because PHP does not have regular classes Set '/XXX/' and '# XXX #' to regular expressions * 2. default parameters: for example, '/{id}' => array ('id' => '/\ d +/', '_ m' => 'frontpage ', '_ A' => 'index') is used as an example.' _ m' => 'frontpage 'is a default parameter. * because the preceding path does not have information about _ m and _, therefore, the default parameters will be used as the values of _ m and _ a **. Therefore, for the rule '/{id}' => array ('id' => '/\ d +/ ', '_ m' => 'frontpage',' _ A' => 'index '). When I pass in/3, the system will convert to index. php? _ M = frontpage & _ a = index & id = 3 ** rule matching is performed one by one in the order of the $ routes array. Once matched, the rule does not match any more. Therefore, some specific matching rules should be put at the front and general rules should be put at the back. * Otherwise, the specified matching rule may not be executed */$ 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. the most complex and important part of the routing mechanism is the parser.
The parser consists of two classes (the name may not be good ).
One is Route, which serves as the external interface of the whole parser for parsing rules, matching and transforming URLs. However, it is only a proxy and the actual operation is not directly done by it.
One is RoutePattern, and each RoutePattern instance corresponds to a record in the rule array. one Route instance contains multiple RoutePattern, and all operations in the Route will call all operations in the internal RoutePattern instance for integration.
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);}/*** use routing rules to match the corresponding url address, after successful match, put the corresponding url parameter in $ _ GET * @ param string url address * @ return bool: whether the match is successful */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 {//......}

The main details about the parsing of the route configuration file are in RoutePattern-like. the length and energy of RoutePattern's rule parsing, URL matching, and URL conversion are limited. I will not detail it today, next, analyze it carefully.
My Weibo address is http://weibo.com/jameren. welcome to everyone's website and visit lol :.
By the way, make an advertisement:

Reference


I recently used a 15 GB ultra-high-space free web USB flash drive-@ cool disk, which can be used on PCs and mobile phones. it has no file type and size restrictions. it delivers fast transmission speeds and never loses files, let's try it together! Register through the invitation link below, and you and I will get an additional MB of cool disk space! Http://t.cn/aNLZje

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.