Home > Backend Development > PHP Tutorial > Introduction to the mechanism of implementing simple pseudo-static URL in PHP

Introduction to the mechanism of implementing simple pseudo-static URL in PHP

WBOY
Release: 2016-07-25 09:05:30
Original
1303 people have browsed it
  1. RewriteEngine On
  2. RewriteRule ^index.php$ - [L]
  3. RewriteCond %{REQUEST_FILENAME} !-f
  4. RewriteCond %{REQUEST_FILENAME} !-d
  5. RewriteRule (.+) index.php/$1 [L]
Copy code

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

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

  1. /**
  2. * Instructions for writing routing configuration files:
  3. * Routing configuration is in an array array, and one record represents a rule
  4. * The data of the array key represents the matching path format: use a specific string identifier such as: '/{id}'
  5. * The string can contain specific variables, all variables are wrapped in braces {}
  6. * The array value is an array array, which performs specific processing on the variables in the path in the key
  7. * The variables are written in the key of the array, The specification is written in the value of the array, such as: array('id'=>'/d+/','_m'=>'frontpage','_a'=>'index')
  8. * The specification is divided into two categories :
  9. * 1. Format judgment: For example, '/{id}'=> array('id'=>'/d+/','_m'=>'frontpage','_a'=>'index '), for example, 'id'=>'/d+/' is a format judgment,
  10. * means that the id variable can only be a number, and only regular expressions can be used after the format judgment. Since PHP does not have a regular class, I Specify strings in the format of '/XXX/' and '#XXX#' as regular expressions
  11. * 2. Default parameters: For example, '/{id}'=> array('id'=>'/d+/' ,'_m'=>'frontpage','_a'=>'index') for example, where '_m'=>'frontpage' is a default parameter,
  12. * because the previous path does not have _m and _ a information, so the default parameters will be used as the values ​​of _m and _a later
  13. *
  14. * So for the rule '/{id}'=> array('id'=>'/d+/','_m' =>'frontpage','_a'=>'index'). When I pass in /3, the system will convert it into index.php?_m=frontpage&_a=index&id=3
  15. *
  16. * The rule matching is to match one by one in the order of the $routes array. Once matched, it will not match downwards. Therefore, some specific matching rules should be placed at the front and general ones at the back.
  17. * Otherwise, specific matching rules may not be executed
  18. */
  19. $routes= array(
  20. '/' => array('_m'=>'wp_frontpage','_a'=>'index'),
  21. '/{id}'=> array('id'=>'/d+/','_m'=>'wp_frontpage','_a'=>'index'),
  22. '/{_m }/{_a}/{id}'=> array('id'=>'/d+/'),
  23. '/{_m}/{_a}'=> array()
  24. );
Copy code

3. The most complex and important part of the routing mechanism is the parser. The parser consists of two classes (perhaps poorly named). One is Route, which is the external interface of the entire parser and is used to parse rules, match and convert URLs. However, it is just a proxy, and the actual operation is not performed directly by it. One is RoutePattern. Each RoutePattern instance corresponds to a record in the rule array. A Route instance contains multiple RoutePatterns, and all operations in Route will call all internal RoutePattern instance operations and integrate them.

  1. class Route
  2. {
  3. private static $instance = null;
  4. private $routepatterns=array();
  5. private function __construct()
  6. {
  7. $routes = array();
  8. include ROOT."/ routes.php";
  9. foreach($routes as $key=>$value){
  10. $this->routepatterns[]=new RoutePattern($key,$value);
  11. }
  12. if(!isset($ _SERVER['PATH_INFO'])) return false;
  13. $urlpath= $_SERVER['PATH_INFO'];
  14. $ismatch=$this->match_url($urlpath);
  15. $strip_urlpath=str_replace('/','' ,$urlpath);
  16. if(!$ismatch&&!emptyempty($strip_urlpath)){
  17. Content::redirect(PAGE_404);
  18. }
  19. }
  20. /**
  21. * Use routing rules to match the corresponding url address. If the match is successful, put the corresponding url parameters into $_GET
  22. * @param string url address
  23. * @return bool Whether the match is successful
  24. */
  25. public function match_url($urlpath) {
  26. foreach($this->routepatterns as $router){
  27. $urlargs=$router->match_url($urlpath);
  28. if($urlargs!==false){
  29. $_GET=array_merge($urlargs, $_GET);
  30. return true;
  31. }
  32. }
  33. return false;
  34. }
  35. public function rewrite_url($urlparams){
  36. foreach($this->routepatterns as $router){
  37. $urlstr=$router-> ;rewrite_url($urlparams);
  38. if($urlstr!==false){
  39. return $urlstr;
  40. }
  41. }
  42. $actualparams=array();
  43. foreach($urlparams as $arg=>$val){
  44. $actualparams[]=$arg."=".urlencode($val);
  45. }
  46. $actualparamstr=implode('&', $actualparams);
  47. $rewriteurl="/index.php";
  48. if(! emptyempty($rewriteurl))$rewriteurl.="?{$actualparamstr}";
  49. return $rewriteurl;
  50. }
  51. public static function init()
  52. {
  53. if (null == self::$instance) {
  54. self ::$instance = new Route();
  55. }
  56. return self::$instance;
  57. }
  58. }
  59. class RoutePattern{
  60. //...
  61. }
Copy code

About routing The main details of configuration file parsing are all in the RoutePattern class. Regarding the details of rule parsing, URL matching and URL conversion in RoutePattern, the space and energy are limited, so we will not introduce them in detail today. We will analyze them in detail next time.



source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template