PHP simple pseudo-static URL mechanism implementation

Source: Internet
Author: User
Tags new set
Once upon a while, our company was ready to develop a new set of station systems, decided to give the previous framework to KO, and re-develop a new framework to adapt to the new system functions. Leaders do not want to use the outside framework, claiming to develop their own unique framework (the leader who does not understand the development of the killing). So we went into the new development.
Because our system supports pseudo-static, the previous system was directly using the server Apache or IIS rewrite file definition rules, and the framework does not have any routing mechanism, so this framework is ready to use the new policy, PHP implementation of the routing mechanism. So I began to explore the realization of the function of the road.
Before I developed it, I first understood what the ' routing mechanism ' was going to do, and it mainly did two things.
1. Routing mechanism is to extract a particular form of the URL structure of the system corresponding parameters. For example, such as: HTTP://MAIN.WOPOP.COM/ARTICLE/1,/ARTICLE/1, _m=article&id=1.
2. Secondly, the conversion of URLs with corresponding parameters into a specific form of URL structure is the reverse process of the above process. Because the routing mechanism isolates the transformation relationship between the URL structure and the parameters, the subsequent structure changes do not affect the execution of the following code.
With the above understanding, you can draw a few steps to write a routing mechanism:
1. Write the server Apache or IIS rewrite file, and import the URL structure into the index.php.
2. A Routing rule configuration file.
3. A route parser to parse the rules, match and convert URLs.
So, we have each of these parts.

1.rewrite file, take Apache as an example:

<ifmodule mod_rewrite.c>rewriteengine onrewriterule ^index\.php$-[L]rewritecond%{REQUEST_FILENAME}!- Frewritecond%{request_filename}!-drewriterule (. +) index.php/$1 [l]</ifmodule>

The above code is to import the URL structure into the index.php, the specific rewrite details will not be described.

2. Set up a routing rule profile in PHP routes.php, I simply used a hash array to write the rules:

/** * Routing configuration file Description: * Routing configuration in an array arrays, 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} ' * string can contain a specific variable, all variables using curly braces {} Wrap it up. * Array value is an array, which is a specific processing of variables in the path in key * variables written in the array key, specification written in the array of value, such as: Array (' id ' = '/\d+/', ' _m ' = ') FrontPage ', ' _a ' = ' index ') * specifications are divided into two categories: * 1. Format judgment: For example '/{id} ' = = Array (' id ' = ' = '/\d+/', ' _m ' = ' FrontPage ', ' _a ' = > ' index ') for example, where ' id ' = '/\d+/' is a format judgment, * means ID variable can only be a number, the format can only use regular expression after the judgement, because PHP does not have a regular class, so I specify '/xxx/' and ' #XXX # ' The formatted string is a regular expression * 2. Default parameters: such as '/{id} ' = = Array (' id ' = ' = '/\d+/', ' _m ' = ' FrontPage ', ' _a ' = ' index ') for example, where ' _m ' = ' FrontPage ' is a default parameter, * because the previous path does not have _m and _a information, the default parameters are used later as _m and _a values * So for the rule '/{id} ' = = Array (' id ' = = '/\d+/', ' _m ' = ' = ') FrontPage ', ' _a ' = ' index '). My incoming/3 system will be converted to index.php?_m=frontpage&_a=index&id=3 * * Rule matching is matched according to the order of the $routes array, once the match is not matched down. So some of the specific matching rules should be put in front, and the generic ones in the back. * This may result in no specific matching rule being 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 be poor). The
one is the route, which acts as an interface to the entire parser, parsing rules, matching and translating URLs, but it is just a proxy, and the actual operation is not directly done directly by it. The
one is Routepattern, each Routepattern instance corresponds to a record in the rule array, and a route instance contains multiple Routepattern. All operations in the route invoke all internal Routepattern instance operations and are consolidated.

Class Route{private Static $instance = Null;private $routepatterns =array ();p rivate 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);}} /*** matches the corresponding URL address with a routing rule, and the matching URL parameter is successfully placed in the $_get * @param string URL address * @return BOOL matches successfully */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{//...}
  • Related Article

    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.