Thinkphp5 URL and routing functions and examples, thinkphp5url

Source: Internet
Author: User
Tags closure definition

Thinkphp5 URL and routing functions and examples, thinkphp5url

Previous

This article describes thinkphp5URL and routing in detail.

URL access

ThinkPHP uses a single entry mode to access the application. All requests to the application are directed to the application's entry file. The system will parse the module, Controller, and operation of the current request from the URL parameter, the following is a standard url access format:

Http: // domainName/index. php/module/controller/Operation

Index. php is called the application's entry file (note that the entry file can be hidden and will be mentioned later)

The concept of a module in ThinkPHP is actually a subdirectory under the application directory, and the official specification is that the directory name is in lower case. Therefore, all modules are named in lower case, regardless of whether the URL is case-insensitive, the module names are forcibly lowercase.

The index controller of the Index module of the application is defined as follows:

<?php
namespace app\index\controller;
class Index
{
  public function index()
  {
    return 'index';
  }
  public function hello($name = 'World')
  {
    return 'Hello,' . $name . '!';
  }
}

If you directly access the entry file, the system will access the default operation (index) of the default controller (Index) under the default module (index) because there are no modules, controllers, and operations in the URL ), therefore, the following access is equivalent:

Http://tp5.com/index.php
Http://tp5.com/index.php/index/index/index

If you want to access the hello method of the controller, you need to use the complete URL address.

Http://tp5.com/index.php/index/index/hello/name/thinkphp

After accessing the URL address, the page output result is:

Hello, thinkphp!

Because the name parameter is optional, you can also use

Http://tp5.com/index.php/index/index/hello

After accessing the URL address, the page output result is:

Hello, World!

By default, the Controller and operation name in the URL address are case-insensitive, so the following access is actually equivalent:

Http://tp5.com/index.php/index/Index/Index
Http://tp5.com/index.php/index/INDEX/INDEX

If the controller is camped, for example, define a HelloWorld controller (application/index/controller/HelloWorld. php ):


 
<?php
namespace app\index\controller;
class HelloWorld
{
  public function index($name = 'World')
  {
    return 'Hello,' . $name . '!';
  }
}

The correct URL access address (which can be generated using the url method) should be

Http://tp5.com/index.php/index/hello_world/index

The system automatically locates the HelloWorld controller class for operations.

If you use

Http://tp5.com/index.php/index/HelloWorld/index

An error is reported and the Helloworld controller class does not exist.

If you want to strictly distinguish case-sensitive access (in this way, controller access can be supported by the hump method), you can set it in the application configuration file:

/ / Turn off URL automatic conversion (support hump access controller)
'url_convert' => false,

After automatic URL conversion is disabled, the following URL must be used for access (the Controller name must strictly use the name of the controller class, excluding the Controller suffix ):

Http://tp5.com/index.php/index/Index/index
Http://tp5.com/index.php/index/HelloWorld/index

If the server environment does not support URL access in pathinfo mode, you can use compatibility methods, such:

Http://tp5.com/index.php? S =/index/Index/index

Where the variable s name can be configured

5.0 no longer supports common URL access methods, so the following access is invalid. You will find that no matter what you enter, the access is a default controller and operation.

Http://tp5.com/index.php? M = index & c = Index & a = hello

Parameter input

The parameter binding function of the operation method can automatically obtain URL parameters. The controller code is as follows:

<?php
Namespace app\index\controller;
Class Index
{
   Public function index()
   {
     Return 'index';
   }
   Public function hello($name = 'World')
   {
     Return 'Hello,' . $name . '!';
   }
}

When we access

Http://tp5.com/index.php/index/index/hello

Is to access the hello method of the app \ index \ controller \ Index controller class. Because no parameter is input, the name parameter uses the default value World. If the name parameter is input, use:

Http://tp5.com/index.php/index/index/hello/name/thinkphp

The page output result is:

Hello, thinkphp!

Now add the second parameter to the hello method:

public function hello($name = 'World', $city = '')
  {
    return 'Hello,' . $name . '! You come from ' . $city . '.';
  }

The access address is http://tp5.com/index.php/index/index/hello/name/thinkphp/city/shanghai

The page output result is:

Hello, thinkphp! You come from shanghai.

As you can see, the hello method automatically obtains the parameter value of the same name in the URL address as the parameter value of the method, and the input sequence of this parameter is not affected by the URL parameter order, for example, the output result of the following URL address is the same as that above:

Http://tp5.com/index.php/index/index/hello/city/shanghai/name/thinkphp

Or use http://tp5.com/index.php/index/index/hello? City = shanghai & name = thinkphp

We can further simplify the URL, on the premise that we must specify the variables represented by the order of parameters. We can change the URL parameter acquisition method, modify the value of url_param_type in the application configuration file as follows:

// Obtain 'url _ param_type '=> 1,

Now, the parameter value passing method of the URL is changed to passing the value strictly according to the variable definition sequence of the operation method, that is to say, we must use the following URL to access in order to pass the name and city parameters to the hello method: http://tp5.com/index.php/index/index/hello/thinkphp/shanghai

The page output result is:

Hello, thinkphp! You come from shanghai.

If you change the order of parameters to http://tp5.com/index.php/index/index/hello/shanghai/thinkphp

The page output result is:

Hello, shanghai! You come from thinkphp.

Obviously it is not our expected result.

Similarly, we try to pass through the http://tp5.com/index.php/index/index/hello/name/thinkphp/city/shanghai

The access will not get the correct result.

[Note] If parameters are bound in order, the parameters of the operation method can only use URL pathinfo variables, but not get or post variables.

Hide entries

You can remove index. php from the URL file, but you need to configure Rewrite Rules for the WEB server.

Take Apache as an example. You need to add the. htaccess file at the same level of the entry file (this file is provided by the official system by default). The content is as follows:

<IfModule mod_rewrite.c>
Options +FollowSymlinks -Multiviews
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php/$1 [QSA,PT,L]
</IfModule>

If phpstudy is used, the rules are as follows:

<IfModule mod_rewrite.c> 
Options +FollowSymlinks -Multiviews 
RewriteEngine on 
RewriteCond %{REQUEST_FILENAME} !-d 
RewriteCond %{REQUEST_FILENAME} !-f 
RewriteRule ^(.*)$ index.php [L,E=PATH_INFO:$1] 
</IfModule>

Next, you can use the following URL to access

Http://tp5.com/index/index/index
Http://tp5.com/index/index/hello

If index. php cannot be properly hidden using the above method in the apache version, you can try the following method to configure the. htaccess file:

<IfModule mod_rewrite.c>
Options +FollowSymlinks -Multiviews
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php?/$1 [QSA,PT,L]
</IfModule>

In the Nginx environment, you can add:

Location / { // ..... omit part of the code
   If (!-e $request_filename) {
     Rewrite ^(.*)$ /index.php?s=/$1 last;
     Break;
   }
}

Define a route

How can the index module in the URL address be omitted? The default URL address is a little long. The following describes how to simplify URL access through routing.

We add some routing rules in the routing definition file (application/route. php), as follows:

Return [
   / / Add routing rules routing hello operation method to the index controller
   'hello/:name' => 'index/index/hello',
];

This routing rule indicates that all accesses with parameters starting with "hello" are routed to the "hello" Operation Method of the index controller.

URL access address before routing is: http://tp5.com/index/index/hello/name/thinkphp

After you define a route, you can only access the following URL address http://tp5.com/hello/thinkphp

[Note] after a routing rule is defined, the original URL address becomes invalid and becomes an invalid request.

But there is a small problem here if we just access the http://tp5.com/hello

An error will occur

In fact, this is because the route does not match correctly. we modify the routing rules as follows:

Return [// The route parameter name is optional 'Hello/[: name] '=> 'index/hello',];

Use [] to wrap the variable in the routing rule, it means the variable is optional, then you can access the http://tp5.com/hello normally

When the name parameter does not pass in a value, the name parameter of the hello method has the default value "World", so the output content is "Hello, World!

In addition to the definition in the routing configuration file, you can also dynamically define routing rules. For example, you can add the following method directly at the beginning of the routing configuration file (application/route. php:

use think\Route;Route::rule('hello/:name', 'index/hello');

The effect is the same as that defined in the configuration method.

Both the configuration method and the Route class method are used to define routes and put them in the routing configuration file application/route. php.

[Note] the routing configuration cannot be set in the module configuration file.

[Complete match]

The previously defined route can be matched as long as it starts with hello. If you need a complete match, you can use the following definition:

Return [// The route parameter name is optional 'Hello/[: name] $ '=> 'index/hello',];

When a routing rule ends with $, it indicates that the current routing rule needs to be completely matched.

When we access the following URL:

Http://tp5.com/hello // correct match
Http://tp5.com/hello/thinkphp // correct match
Http://tp5.com/hello/thinkphp/val/value // does not match

Closure Definition]

You can also define routing rules for some special scenarios by defining closures. For example:

Return [// define the closure 'Hello/[: name] '=> function ($ name) {return 'hello,'. $ name .'! ';},];

Or

use think\Route;Route::rule('hello/:name', function ($name) {  return 'Hello,' . $name . '!';});

[Note] the parameters of the closure function are the variables defined in the routing rules.

Therefore, when accessing the following URL address: http://tp5.com/hello/thinkphp

Output

Hello, thinkphp!

[Set URL separator]

To change the pathinfo parameter Separator in the URL, you only need to set it in the application configuration file (application/config. php:

// Set the pathinfo separator 'pathinfo _ depr' => '-',

The routing rule definition can access the following address without any changes: http://tp5.com/hello-thinkphp

[Route parameters]

You can also restrict the request type or URL Suffix of a routing rule, for example:

Return [// define the request type and suffix 'Hello/[: name] '=> ['index/hello', ['method' => 'get ', 'text' => 'html '],];

The routing rule defined above limits that the request must be a get request and the suffix must be html, so the following access address:

Http://tp5.com/hello // invalid
Http://tp5.com/hello.html // valid
Http://tp5.com/hello/thinkphp // invalid
Http://tp5.com/hello/thinkphp.html // valid

Variable rules]

Next, try to define some complex routing rules to meet different routing variables. Before that, add a controller class as follows:

<?php
Namespace app\index\controller;
Class blog
{
Public function get($id)
{
Return 'View id=' . $id . 'Content';
}
Public function read($name)
{
Return 'View name=' . $name . 'Content';
}
Public function archive($year, $month)
{
Return 'View' . $year . '/' . $month . 'Archived content';
}
}

Add the following routing rules:

return [
  'blog/:year/:month' => ['blog/archive', ['method' => 'get'], ['year' => '\d{4}', 'month' => '\d{2}']],
  'blog/:id'     => ['blog/get', ['method' => 'get'], ['id' => '\d+']],
  'blog/:name'    => ['blog/read', ['method' => 'get'], ['name' => '\w+']],
];

In the preceding routing rules, we impose rule constraints on variables. Variable rules are defined using regular expressions.

Let's take a look at several URL accesses.

// Access content with id 5
Http://tp5.com/blog/5
// Access thinkphp content
Http://tp5.com/blog/thinkphp
// Access the archive content in May 2015
Http://tp5.com/blog/2015/05

[Route group]

The above three routing rules are all blog headers, so we can simplify them as follows:

return [
  '[blog]' => [
    ':year/:month' => ['blog/archive', ['method' => 'get'], ['year' => '\d{4}', 'month' => '\d{2}']],  
    ':id'     => ['blog/get', ['method' => 'get'], ['id' => '\d+']],
    ':name'    => ['blog/read', ['method' => 'get'], ['name' => '\w+']],
  ],
];

For this definition method, we call it a routing group. The routing group can improve the efficiency of routing detection to a certain extent.

[Complex routing]

Sometimes, you also need to customize the URL. For example, if you want to support the following access addresses at the same time

Http://tp5.com/blog/thinkphp
Http://tp5.com/blog-2015-05

We only need to slightly change the routing definition rules:

return [
  'blog/:id'      => ['blog/get', ['method' => 'get'], ['id' => '\d+']],
  'blog/:name'     => ['blog/read', ['method' => 'get'], ['name' => '\w+']],
  'blog-<year>-<month>' => ['blog/archive', ['method' => 'get'], ['year' => '\d{4}', 'month' => '\d{2}']],
];

For abnormal specifications such as blog-<year>-<month>, we need to use the variable definition method such as <variable name> instead of the variable name method.

For simplicity, we can also define variable rules in a unified manner, for example:

Return [
   // global variable rule definition
   '__pattern__' => [
     'name' => '\w+',
     'id' => '\d+',
     'year' => '\d{4}',
     'month' => '\d{2}',
   ],
   // routing rule definition
   'blog/:id' => 'blog/get',
   'blog/:name' => 'blog/read',
   'blog-<year>-<month>' => 'blog/archive',
];

The variable rules defined in _ pattern _ are called global variable rules. The variable rules defined in routing rules are called local variable rules, if a variable defines both global rules and local rules, the current local rules will overwrite the global rules. For example:

Return [
   // global variable rules
   '__pattern__' => [
     'name' => '\w+',
     'id' => '\d+',
     'year' => '\d{4}',
     'month' => '\d{2}',
   ],
 
   'blog/:id' => 'blog/get',
   / / Defined a local variable rule
   'blog/:name' => ['blog/read', ['method' => 'get'], ['name' => '\w{5,}']],
   'blog-<year>-<month>' => 'blog/archive',
];

URL generation

After defining a routing rule, you can use the Url class to easily generate the actual URL address (route address). For the preceding routing rule, we can generate the URL address in the following way.

// output blog/thinkphp
Url::build('blog/read', 'name=thinkphp');
Url::build('blog/read', ['name' => 'thinkphp']);
// output blog/5
Url::build('blog/get', 'id=5');
Url::build('blog/get', ['id' => 5]);
// output blog/2015/05
Url::build('blog/archive', 'year=2015&month=05');
Url::build('blog/archive', ['year' => '2015', 'month' => '05']);

[Note] the first parameter of the build method uses the complete route address in the route definition.

You can also use the assistant function url provided by the system to simplify the process.

Url ('blog/read', 'name = thinkphp'); // equivalent to Url: build ('blog/read', 'name = thinkphp ');

You can use helper functions for output in a template file, for example:

{:url('blog/read', 'name=thinkphp')}

If our routing rules are adjusted, the generated URL address will automatically change.

If you configure the url_html_suffix parameter, the generated URL address carries a suffix, for example:

'url_html_suffix'  => 'html',

The generated URL address is similar

blog/thinkphp.html blog/2015/05.html

If all your URL addresses are defined in the routing mode, you can also use routing rules to define URL generation. For example:

url('/blog/thinkphp');Url::build('/blog/8');Url::build('/blog/archive/2015/05');

The first parameter of the generation method must be consistent with the route address defined by the route. If your route address is special, such as the closure definition, You need to manually specify an identifier for the route, for example:

/ / Add hello route identifier
Route::rule(['hello','hello/:name'], function($name){
   Return 'Hello,'.$name;
});
// Quickly generate a URL based on the route ID
Url::build('hello', 'name=thinkphp');
// or use
Url::build('hello', ['name' => 'thinkphp']); 

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.


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.