ThinkPHP3.1 quick start (6) routing

Source: Internet
Author: User
The ThinkPHP framework has certain specifications for URLs. if you want to customize your URL format, you need to have a good understanding of the built-in routing function, it makes your URL more concise and cultural. The ThinkPHP framework has certain specifications for URLs. if you want to customize your URL format, you need to have a good understanding of the built-in routing function, it makes your URL more concise and cultural.

To enable routing, you must use the routing function, provided that your URL supports PATH_INFO and enable routing in the project configuration file:
  1. 'URL _ ROUTER_ON '=> true, // enable routing
Copy the code and configure the routing rules. URL_ROUTE_RULESParameter configuration. the configuration format is an array. each element represents a routing rule. for example:
  1. 'URL _ ROUTE_RULES '=> array (
  2. 'News/: year/: month/: day' => array ('news/archive', 'status = 1 '),
  3. 'News/: ID' => 'news/read ',
  4. 'News/read/: ID' => '/news/: 1 ',
  5. ),
The copy code system matches the routing rules in the defined order. Once the rules are matched, the module (group supported) and Operation method in the routing definition are located for execution, in addition, the following rules do not continue to match.

The routing rule is defined as follows:
  1. 'Route expression'=>'Route address and additional parameters'
The copy code routing expression includes the rule routing and regular routing definition expressions, and can only use strings.
Expression Example
Regular expression /^ Blog \/(\ d +) $/
Rule expression Blog/: id
Regular expression
The regular expressions supported by the routing expression must start with "/". Otherwise, it is regarded as a rule expression. That is to say, if you use
  1. '# ^ Blog \/(\ d +) $ #'
Regular expressions defined by the replication code method are not supported, but are considered as rule expressions for parsing and thus cannot be correctly matched.
  1. '/^ New \/(\ d {4}) \/(\ d {2}) $/' => 'news/achive? Year =: 1 & month =: 2 ',
Copy the code for each variable in the regular expression (that is, the sub-mode in the regular expression), if you need to reference it in the following routing address, you can use: 1,: 2, the serial number is the serial number of the sub-mode.
More details about how to define regular expressions are beyond the scope described in this article.

Rule expression
3.0 of the rule routes evolved from 2.1 of simple routes. Although the regular routing function cannot be perfectly implemented, it is indeed much more powerful than simple routing, it is easier to define and understand than regular routing.
A rule expression usually contains a static address and a dynamic address, or a combination of the two addresses. for example, the following are valid rule expressions:
  1. 'My => 'Member/myinfo', // The static address routing is similar to the simple routing in the previous version.
  2. 'Blog/: ID' => 'blog/read', // combine static and dynamic addresses
  3. 'New/: year/: month/: day' => 'news/read', // combine static and dynamic addresses
  4. ': User/: blog_id' => 'blog/read', // full dynamic address
Copy the definition of the code rule expression with "/" as the parameter delimiter (no matter what your URL_PATHINFO_DEPR settings are, make sure that you use "/" to separate URL parameters when defining rule expressions ).
Parameters starting with ":" In each parameter indicate dynamic parameters and automatically correspond to a GET parameter. for example: id indicates that the matched parameters can be obtained using $ _ GET ['id'], year: month: day corresponds to $ _ GET ['Year'] $ _ GET ['month'] $ _ GET ['day'].

Number constraints
Supports variable type detection, but only supports numerical type constraints, such
  1. 'Blog/: id \ d' => 'blog/read ',
Copy the code to match only numeric parameters. if you need more variable types, use the regular expression definition.

Rule exclusion
Non-numeric variables support the simple exclusion function, mainly to avoid parsing confusion, for example:
  1. 'News/: cate ^ add | edit | delete' => 'news/category'
Because of the limitations of Rule definition, the replication code is named in the same way as the actual news module in our routing rules: cate does not automatically distinguish the dynamic parameters in the current URL from the actual operation name or route variable. to avoid confusion, we need to exclude the route variable cate to help us perform more precise route matching. the format is ^ add | edit | delete, which matches all strings except add edit and delete, we recommend that you better improve your routing rules to avoid the existence of routing rules with the same name as the module, such
  1. 'New/: cate' => 'news/category'
Copy the code to define routing rules more easily.

Exact match
During rule matching detection, the URL is matched from the beginning. as long as the URL address contains the defined routing rule, the matching succeeds. if you want to completely match the rule, you can use the $ symbol. for example:
  1. 'New/: cate $ '=> 'news/category ',
Copy code
  1. Http: // serverName/index. php/new/info
The copied code will match successfully.
While
  1. Http: // serverName/index. php/new/info/2
The copied code will not match
If you use
  1. 'New/: cate' => 'news/category ',
If you copy the code method definition, both methods of URL access can be matched successfully. The routing address and the additional parameter indicate the address to which the previous routing expression finally needs to be routed and some parameters not included in the URL can be implicitly imported, strings or arrays can be used for definition. the following five methods are supported:
Definition method Definition Format
Method 1: route to the internal address (string) '[Group/module/operation]? Extra parameter 1 = value 1 & additional parameter 2 = value 2 ...'
Method 2: Route to internal address (array) parameters in string mode Array ('[group/module/operation]', 'additional parameter 1 = value 1 & additional parameter 2 = value 2 ...')
Method 3: Route to internal address (array) parameters in array mode Array ('[group/module/operation]', array ('additional parameter 1' => 'value 1 ', 'Additional parameter 2' => 'value 2 '...))
Method 4: Route to external address (string) 301 redirection 'External address'
Method 5: You can specify the redirection code by routing to an external address (array ). Array ('external address', 'redirection code ')
If the route address starts with "/" or "http", it is considered as a redirection address or an external address. for example:
  1. 'Blog/: ID' => '/blog/read/id/: 1'
Copy code and
  1. 'Blog/: ID' => 'blog/read /'
Although all the copied code is routed to the same address, the former uses a 301 redirection route jump, the advantage of this method is that the URL can be more casual (including more parameters in non-standard format can be input in the URL), while the latter only supports the module and Operation address. For example, if we want to redirect avatar/123
/Member/avatar/id/123_small can only be used:
  1. 'Avatar/: ID' => '/member/avatar/id/: too small'
If the routing address of the Copy code uses a redirection address, dynamic variables are also referenced in the following ways: 1 and: 2.

Redirection to an external address is usually useful for the URL migration process after the website is revised. for example:
  1. 'Blog/: ID' => 'http: // blog.thinkphp.cn/read/:1'
Copy the code to indicate that the blog/123 address of the current website (possibly a http://thinkphp.cn) is redirected directly to http://blog.thinkphp.cn/read/123.

During route jump, additional parameter pairs are supported. (additional parameters refer to parameters not included in the URL. implicit input requires operations, which sometimes play a certain role in security protection, we will mention later), supporting "additional parameter 1 = value 1 & additional parameter 2 = value 2" or array ('additional parameter 1' => 'value 1 ', 'Additional parameter 2' => 'value 2 '...) you can select different definition methods. For example:
  1. 'Blog/: ID' => 'blog/read /? Status = 1 & app_id = 5 ',
  2. 'Blog/: ID' => array ('blog/read /? Status = 1 & app_id = 5 '),
  3. 'Blog/: ID' => array ('blog/read/', 'status = 1 & app_id = 5 '),
  4. 'Blog/: ID' => array ('blog/read/', array ('status' => 1, 'app _ id' => 5 )),
The value transfer method for additional parameters in the routing rule definition above the Copy code is equivalent. The status and app_id parameters do not exist in the URL and are implicitly passed values. of course they are not necessarily needed, but can be used only when needed.

The instance description explains how to define routing rules through the above explanation. The following is an example to help you better understand the concept.
Suppose we have defined the News controller as follows (the code implementation is for reference only ):
  1. Class NewsAction extends Action {
  2. Public function read (){
  3. $ New = M ('New ');
  4. If (isset ($ _ GET ['id']) {
  5. // Query results by id
  6. $ Data = $ New-> find ($ _ GET ['id']);
  7. } Elseif (isset ($ _ GET ['name']) {
  8. // Query results by name
  9. $ Data = $ New-> getByName ($ _ GET ['name']);
  10. }
  11. $ This-> data = $ data;
  12. $ This-> display ();
  13. }
  14.  
  15. Public function archive (){
  16. $ New = M ('New ');
  17. $ Year = $ _ GET ['Year'];
  18. $ Month = $ _ GET ['month'];
  19. $ Begin_time = strtotime ($ year. $ month. "01 ");
  20. $ End_time = strtotime ("+ 1 month", $ begin_time );
  21. $ Map ['create _ time'] = array ('GT ', $ begin_time), array ('Lt', $ end_time ));
  22. $ Map ['status'] = 1;
  23. $ List = $ New-> where ($ map)-> select ();
  24. $ This-> list = $ list;
  25. $ This-> display ();
  26. }
  27. }
Copy the code to define the routing rules as follows:
  1. 'URL _ route_rules' => array (// define routing rules
  2. 'New/: id \ d' => 'news/read ',
  3. 'New/: name' => 'news/read ',
  4. 'New/: year \ d/: month \ d' => 'news/archive ',
  5. ),
Copy the code and visit:
  1. Http: // serverName/index. php/new/8
The copied code matches the first routing rule. the actual execution result is equivalent to access:
  1. Http: // serverName/index. php/News/read/id/8
Copy the code when accessing:
  1. Http: // serverName/index. php/new/hello
The copied code matches the second routing rule. the actual execution result is equivalent to access:
  1. Http: // serverName/index. php/News/read/name/hello
Copy the code so if you access:
  1. Http: // serverName/index. php/new/2012/03
Will the copied code match the third routing rule? We expect the actual execution effect to be equivalent to access:
  1. Http: // serverName/index. php/News/archive/year/2012/month/03
The code is actually not copied because http: // serverName/index. php/new/2012/the URL has matched the first routing rule first in the route matching process, and 2012 is passed as the id value, this is a conflict of routing rules. There are two solutions:
1. adjust the definition order
Change the route definition:
  1. 'URL _ route_rules' => array (// define routing rules
  2. 'New/: year \ d/: month \ d' => 'news/archive ',
  3. 'New/: id \ d' => 'news/read ',
  4. 'New/: name' => 'news/read ',
  5. ),
Copy the code and then, when we access again:
  1. Http: // serverName/index. php/new/2012/03
When the code is copied, the expected access effect is achieved. Therefore, if there is a possibility of Rule conflict, we should try to put the complicated rule definitions in front to ensure that the most complex rules can be matched first. However, if more routing rules are defined, they are still confusing. Therefore, you need to find a better solution.
2. use the full match function
Now we can use the fully-matched routing definition function to change the routing definition:
  1. 'URL _ route_rules' => array (// define routing rules
  2. 'New/: id \ d $ '=> 'news/read ',
  3. 'New/: name $ '=> 'news/read ',
  4. 'New/: year \ d/: month \ d $ '=> 'news/archive ',
  5. ),
After the code is added with the $ symbol at the end of the rule, it indicates that the current routing rule is fully matched, and the rule definition conflict can be avoided. For rule routing, the number of parameters or type constraints in the URL must be completely consistent.
Therefore, if we access
  1. Http: // serverName/index. php/new/2012/03/01
If the code is copied, no route is matched.
3. use regular routing
Of course, there are always more than one solution to the problem. in complex cases, do not forget to use the regular routing rule definition. when you cannot find a solution, regular routing can always help you.
To implement the same routing function above, you can also use the following rule definition:
  1. 'URL _ route_rules' => array (// define routing rules
  2. '/^ New \/(\ d +) $/' => 'news/read? Id =: 1 ',
  3. '/^ New \/(\ w +) $/' => 'news/read? Name =: 1 ',
  4. '/^ New \/(\ d {4}) \/(\ d {2}) $/' => 'news/achive? Year =: 1 & month =: 2 ',
  5. ),

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.