Home Backend Development PHP Tutorial Detailed explanation and examples of thinkphp5 URL and routing functions

Detailed explanation and examples of thinkphp5 URL and routing functions

Apr 28, 2018 pm 03:49 PM
php thinkphp5 Example

This article mainly introduces the functional details and examples of thinkphp5 URL and routing. Now I share it with you and give it as a reference. Let’s take a look together

What we said before

This article will introduce 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 entry file of the application. The system will parse the currently requested module, controller and operation from the URL parameters. The following is a standard URL access Format:

http://domainName/index.php/模块/控制器/操作
Copy after login

The index.php is called the entry file of the application (note that the entry file can be hidden, which will be mentioned later)

The concept of module in ThinkPHP is actually a subdirectory under the application directory, and the official specification is that the directory name is lowercase, so the modules are all named in lowercase. Regardless of whether the URL case conversion is turned on, the module name will be forced to lowercase

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

<?php
namespace app\index\controller;
class Index
{
  public function index()
  {
    return &#39;index&#39;;
  }
  public function hello($name = &#39;World&#39;)
  {
    return &#39;Hello,&#39; . $name . &#39;!&#39;;
  }
}
Copy after login
Copy after login

If you access the entry file directly, since there are no modules, controllers and operations in the URL, Therefore, the system will access the default operation (index) of the default controller (Index) under the default module (index), so 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!

Since the name parameter is an optional parameter, 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 names in the URL address are not case-sensitive, so the following accesses are actually equivalent:

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

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

<?php
namespace app\index\controller;
class HelloWorld
{
  public function index($name = &#39;World&#39;)
  {
    return &#39;Hello,&#39; . $name . &#39;!&#39;;
  }
}
Copy after login

Correct URL access address (this address can use url Method generation) should be

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

The system will automatically locate the HelloWorld controller class to operate

If you use

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

, an error will be reported and the Helloworld controller class does not exist

If you want strict case-sensitive access (so that you can support camel case for controller access), you can set it in the application configuration file:

// 关闭URL自动转换(支持驼峰访问控制器)
&#39;url_convert&#39; => false,
Copy after login

Turn off URL auto After conversion, the following URL address must be used to access (the controller name must strictly use the name of the controller class and does not include 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 pathinfo URL access, you can use the compatible method, for example:

http://tp5.com/index.php?s=/index/Index/index

The name of the variable s can be configured

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

http://tp5.com/index.php?m=index&c =Index&a=hello

Parameters passed in

#Through the parameter binding function of the operation method, the parameters of the URL can be automatically obtained, still using the above control Taking the controller as an example, the controller code is as follows:

<?php
namespace app\index\controller;
class Index
{
  public function index()
  {
    return &#39;index&#39;;
  }
  public function hello($name = &#39;World&#39;)
  {
    return &#39;Hello,&#39; . $name . &#39;!&#39;;
  }
}
Copy after login
Copy after login

When we visit

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

is to access the hello method of the app\index\controller\Index controller class. Since no parameters are passed in, the name parameter uses the default value World. If the name parameter is passed in, use:

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

The page output result is:

Hello, thinkphp!

Now add a second parameter to the hello method:

public function hello($name = &#39;World&#39;, $city = &#39;&#39;)
  {
    return &#39;Hello,&#39; . $name . &#39;! You come from &#39; . $city . &#39;.&#39;;
  }
Copy after login

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

The output result of the page is:

Hello, thinkphp! You come from shanghai.

As you can see, the hello method will automatically obtain the parameter value with the same name in the URL address as the parameter value of the method, and the order in which this parameter is passed is not affected by the order of the URL parameters. For example, the result output by the URL address below is the same as the above one. Same:

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

You can also further simplify the URL address. The premise is that we must clarify the variables represented by the order of the parameters. We change the way to obtain the URL parameters. , modify the value of the url_param_type parameter in the application configuration file as follows:

// 按照参数顺序获取
&#39;url_param_type&#39; => 1,
Copy after login

现在,URL的参数传值方式就变成了严格按照操作方法的变量定义顺序来传值了,也就是说我们必须使用下面的URL地址访问才能正确传入name和city参数到hello方法:http://tp5.com/index.php/index/index/hello/thinkphp/shanghai

页面输出结果为:

Hello,thinkphp! You come from shanghai.

如果改变参数顺序为http://tp5.com/index.php/index/index/hello/shanghai/thinkphp

页面输出结果为:

Hello,shanghai! You come from thinkphp.

显然不是我们预期的结果。

同样,我们试图通过http://tp5.com/index.php/index/index/hello/name/thinkphp/city/shanghai

访问也不会得到正确的结果

[注意]按顺序绑定参数的话,操作方法的参数只能使用URL pathinfo变量,而不能使用get或者post变量

隐藏入口

可以去掉URL地址里面的入口文件index.php,但是需要额外配置WEB服务器的重写规则。

以Apache为例,需要在入口文件的同级添加.htaccess文件(官方默认自带了该文件),内容如下

<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>
Copy after login

如果用的phpstudy,规则如下:

<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>
Copy after login

接下来就可以使用下面的URL地址访问了

http://tp5.com/index/index/index
http://tp5.com/index/index/hello

如果使用的apache版本使用上面的方式无法正常隐藏index.php,可以尝试使用下面的方式配置.htaccess文件:

<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>
Copy after login

如果是Nginx环境的话,可以在Nginx.conf中添加:

location / { // …..省略部分代码
  if (!-e $request_filename) {
    rewrite ^(.*)$ /index.php?s=/$1 last;
    break;
  }
}
Copy after login

定义路由

URL地址里面的index模块怎么才能省略呢,默认的URL地址显得有点长,下面就来说说如何通过路由简化URL访问。

我们在路由定义文件(application/route.php)里面添加一些路由规则,如下:

return [
  // 添加路由规则 路由到 index控制器的hello操作方法
  &#39;hello/:name&#39; => &#39;index/index/hello&#39;,
];
Copy after login

该路由规则表示所有hello开头的并且带参数的访问都会路由到index控制器的hello操作方法。

路由之前的URL访问地址为:http://tp5.com/index/index/hello/name/thinkphp

定义路由后就只能访问下面的URL地址http://tp5.com/hello/thinkphp

[注意]定义路由规则后,原来的URL地址将会失效,变成非法请求。

但这里有一个小问题,如果我们只是访问http://tp5.com/hello

将发生错误

事实上这是由于路由没有正确匹配到,我们修改路由规则如下:

return [
  // 路由参数name为可选
  &#39;hello/[:name]&#39; => &#39;index/hello&#39;,
];
Copy after login

使用[]把路由规则中的变量包起来,就表示该变量为可选,接下来就可以正常访问了http://tp5.com/hello

当name参数没有传入值的时候,hello方法的name参数有默认值World,所以输出的内容为 Hello,World!

除了路由配置文件中定义之外,还可以采用动态定义路由规则的方式定义,例如在路由配置文件(application/route.php)的开头直接添加下面的方法:

use think\Route;
Route::rule(&#39;hello/:name&#39;, &#39;index/hello&#39;);
Copy after login

完成的效果和使用配置方式定义是一样的。

无论是配置方式还是通过Route类的方法定义路由,都统一放到路由配置文件application/route.php文件中

[注意]路由配置不支持在模块配置文件中设置

【完整匹配】

前面定义的路由是只要以hello开头就能进行匹配,如果需要完整匹配,可以使用下面的定义:

return [
  // 路由参数name为可选
  &#39;hello/[:name]$&#39; => &#39;index/hello&#39;,
];
Copy after login

当路由规则以$结尾的时候就表示当前路由规则需要完整匹配。

当我们访问下面的URL地址的时候:

http://tp5.com/hello // 正确匹配
http://tp5.com/hello/thinkphp // 正确匹配
http://tp5.com/hello/thinkphp/val/value // 不会匹配

【闭包定义】

还支持通过定义闭包为某些特殊的场景定义路由规则,例如:

return [
  // 定义闭包
  &#39;hello/[:name]&#39; => function ($name) {
    return &#39;Hello,&#39; . $name . &#39;!&#39;;
  },
];
Copy after login

或者

use think\Route;
Route::rule(&#39;hello/:name&#39;, function ($name) {
  return &#39;Hello,&#39; . $name . &#39;!&#39;;
});
Copy after login

[注意]闭包函数的参数就是路由规则中定义的变量

因此,当访问下面的URL地址:http://tp5.com/hello/thinkphp

会输出

Hello,thinkphp!

【设置URL分隔符】

如果需要改变URL地址中的pathinfo参数分隔符,只需要在应用配置文件(application/config.php)中设置:

// 设置pathinfo分隔符
&#39;pathinfo_depr&#39;     => &#39;-&#39;,
Copy after login

路由规则定义无需做任何改变,我们就可以访问下面的地址:http://tp5.com/hello-thinkphp

【路由参数】

还可以约束路由规则的请求类型或者URL后缀之类的条件,例如:

return [
  // 定义路由的请求类型和后缀
  &#39;hello/[:name]&#39; => [&#39;index/hello&#39;, [&#39;method&#39; => &#39;get&#39;, &#39;ext&#39; => &#39;html&#39;]],
];
Copy after login

上面定义的路由规则限制了必须是get请求,而且后缀必须是html的,所以下面的访问地址:

http://tp5.com/hello // 无效
http://tp5.com/hello.html // 有效
http://tp5.com/hello/thinkphp // 无效
http://tp5.com/hello/thinkphp.html // 有效

【变量规则】

接下来,尝试一些复杂的路由规则定义满足不同的路由变量。在此之前,首先增加一个控制器类如下:

<?php
namespace app\index\controller;
class Blog
{
  public function get($id)
  {
    return &#39;查看id=&#39; . $id . &#39;的内容&#39;;
  }
  public function read($name)
  {
    return &#39;查看name=&#39; . $name . &#39;的内容&#39;;
  }
  public function archive($year, $month)
  {
    return &#39;查看&#39; . $year . &#39;/&#39; . $month . &#39;的归档内容&#39;;
  }
}
Copy after login

添加如下路由规则:

return [
  &#39;blog/:year/:month&#39; => [&#39;blog/archive&#39;, [&#39;method&#39; => &#39;get&#39;], [&#39;year&#39; => &#39;\d{4}&#39;, &#39;month&#39; => &#39;\d{2}&#39;]],
  &#39;blog/:id&#39;     => [&#39;blog/get&#39;, [&#39;method&#39; => &#39;get&#39;], [&#39;id&#39; => &#39;\d+&#39;]],
  &#39;blog/:name&#39;    => [&#39;blog/read&#39;, [&#39;method&#39; => &#39;get&#39;], [&#39;name&#39; => &#39;\w+&#39;]],
];
Copy after login

在上面的路由规则中,我们对变量进行的规则约束,变量规则使用正则表达式进行定义。

我们看下几种URL访问的情况

// 访问id为5的内容
http://tp5.com/blog/5
// 访问name为thinkphp的内容
http://tp5.com/blog/thinkphp
// 访问2015年5月的归档内容
http://tp5.com/blog/2015/05

【路由分组】

上面的三个路由规则由于都是blog打头,所以我们可以做如下的简化:

return [
  &#39;[blog]&#39; => [
    &#39;:year/:month&#39; => [&#39;blog/archive&#39;, [&#39;method&#39; => &#39;get&#39;], [&#39;year&#39; => &#39;\d{4}&#39;, &#39;month&#39; => &#39;\d{2}&#39;]],  
    &#39;:id&#39;     => [&#39;blog/get&#39;, [&#39;method&#39; => &#39;get&#39;], [&#39;id&#39; => &#39;\d+&#39;]],
    &#39;:name&#39;    => [&#39;blog/read&#39;, [&#39;method&#39; => &#39;get&#39;], [&#39;name&#39; => &#39;\w+&#39;]],
  ],
];
Copy after login

对于这种定义方式,我们称之为路由分组,路由分组一定程度上可以提高路由检测的效率

【复杂路由】

有时候,还需要对URL做一些特殊的定制,例如如果要同时支持下面的访问地址

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

我们只要稍微改变路由定义规则即可:

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

对 blog-- 这样的非正常规范,我们需要使用<变量名>这样的变量定义方式,而不是 :变量名方式。

简单起见,我们还可以把变量规则统一定义,例如:

return [
  // 全局变量规则定义
  &#39;__pattern__&#39;     => [
    &#39;name&#39; => &#39;\w+&#39;,
    &#39;id&#39;  => &#39;\d+&#39;,
    &#39;year&#39; => &#39;\d{4}&#39;,
    &#39;month&#39; => &#39;\d{2}&#39;,
  ],
  // 路由规则定义
  &#39;blog/:id&#39;      => &#39;blog/get&#39;,
  &#39;blog/:name&#39;     => &#39;blog/read&#39;,
  &#39;blog-<year>-<month>&#39; => &#39;blog/archive&#39;,
];
Copy after login

在__pattern__中定义的变量规则我们称之为全局变量规则,在路由规则里面定义的变量规则我们称之为局部变量规则,如果一个变量同时定义了全局规则和局部规则的话,当前的局部规则会覆盖全局规则的,例如:

return [
  // 全局变量规则
  &#39;__pattern__&#39;     => [
    &#39;name&#39; => &#39;\w+&#39;,
    &#39;id&#39;  => &#39;\d+&#39;,
    &#39;year&#39; => &#39;\d{4}&#39;,
    &#39;month&#39; => &#39;\d{2}&#39;,
  ],

  &#39;blog/:id&#39;      => &#39;blog/get&#39;,
  // 定义了局部变量规则
  &#39;blog/:name&#39;     => [&#39;blog/read&#39;, [&#39;method&#39; => &#39;get&#39;], [&#39;name&#39; => &#39;\w{5,}&#39;]],
  &#39;blog-<year>-<month>&#39; => &#39;blog/archive&#39;,
];
Copy after login

URL生成

定义路由规则之后,可以通过Url类来方便的生成实际的URL地址(路由地址),针对上面的路由规则,我们可以用下面的方式生成URL地址。

// 输出 blog/thinkphp
Url::build(&#39;blog/read&#39;, &#39;name=thinkphp&#39;);
Url::build(&#39;blog/read&#39;, [&#39;name&#39; => &#39;thinkphp&#39;]);
// 输出 blog/5
Url::build(&#39;blog/get&#39;, &#39;id=5&#39;);
Url::build(&#39;blog/get&#39;, [&#39;id&#39; => 5]);
// 输出 blog/2015/05
Url::build(&#39;blog/archive&#39;, &#39;year=2015&month=05&#39;);
Url::build(&#39;blog/archive&#39;, [&#39;year&#39; => &#39;2015&#39;, &#39;month&#39; => &#39;05&#39;]);
Copy after login

[注意]build方法的第一个参数使用路由定义中的完整路由地址

还可以使用系统提供的助手函数url来简化

url(&#39;blog/read&#39;, &#39;name=thinkphp&#39;);
// 等效于
Url::build(&#39;blog/read&#39;, &#39;name=thinkphp&#39;);
Copy after login

通常在模板文件中输出的话,可以使用助手函数,例如:

{:url(&#39;blog/read&#39;, &#39;name=thinkphp&#39;)}
Copy after login

如果我们的路由规则发生调整,生成的URL地址会自动变化

如果你配置了url_html_suffix参数的话,生成的URL地址会带上后缀,例如:

&#39;url_html_suffix&#39;  => &#39;html&#39;,
Copy after login

那么生成的URL地址 类似

blog/thinkphp.html 
blog/2015/05.html
Copy after login

如果你的URL地址全部采用路由方式定义,也可以直接使用路由规则来定义URL生成,例如:

url(&#39;/blog/thinkphp&#39;);
Url::build(&#39;/blog/8&#39;);
Url::build(&#39;/blog/archive/2015/05&#39;);
Copy after login

生成方法的第一个参数一定要和路由定义的路由地址保持一致,如果你的路由地址比较特殊,例如使用闭包定义的话,则需要手动给路由指定标识,例如:

// 添加hello路由标识
Route::rule([&#39;hello&#39;,&#39;hello/:name&#39;], function($name){
  return &#39;Hello,&#39;.$name;
});
// 根据路由标识快速生成URL
Url::build(&#39;hello&#39;, &#39;name=thinkphp&#39;);
// 或者使用
Url::build(&#39;hello&#39;, [&#39;name&#39; => &#39;thinkphp&#39;]);
Copy after login

相关推荐:

PHP使用Curl实现模拟登录及抓取数据功能示例

The above is the detailed content of Detailed explanation and examples of thinkphp5 URL and routing functions. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1672
14
PHP Tutorial
1276
29
C# Tutorial
1256
24
PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

See all articles