Home Backend Development PHP Tutorial ThinkPHP路由详解_PHP

ThinkPHP路由详解_PHP

May 30, 2016 am 08:46 AM
thinkphp routing

有了基本配置,我们就可以来访问我们的应用默认首页了。进入到项目目录,可以直接使用PHP内置服务器来开始访问,比如:

php -S localhost:8999

Copy after login

浏览器输入localhost:8999就可以看到ThinkPHP的默认首页了:一个笑脸。

在这里,我们访问到的是ThinkPHP自带的默认入口文件index.php也就是访问到的是IndexController的index()方法,这是因为ThinkPHP默认设置:

'DEFAULT_CONTROLLER'  => 'Index'
Copy after login

如果你查看过ThinkPHP/Conf/convention.php文件,应该就会明白这个其实就是设置默认的控制器。

关于控制器(Controller)我们后面会仔细说

了解这些基本知识之后,那么如果我们需要访问其它的页面,访问其他的控制器和方法呢?答案就在本节的路由教程中。

路由定义规则

在使用路由之前,确保你的URL支持PATH_INFO(或者兼容URL模式也可以,采用普通URL模式的情况下不支持路由功能)并且确认已开启一下的路由设置:

'URL_ROUTER_ON'  => true
Copy after login

这里涉及到两个设置项,PATH_INFO和URL_ROUTER_ON,这些在ThinkPHP/Conf/convention.php文件都可以找到。

在满足以上两个条件之后,就可以配置路由规则了。在配置文件中使用URL_ROUTE_RULES参数进行配置,配置格式是一个数组,其格式为: '路由表达式'=>'路由地址和传入参数'每个元素都代表一个路由规则,比如:

'URL_ROUTE_RULES'=>array(
  'blogs/:year/:month/:day' => array('Index/archive', 'status=1'),
  'blogs/:id'        => 'Index/read',
),
Copy after login

ThinkPHP按定义的顺序依次匹配路由规则,一旦匹配到的话,就会定位到路由定义中的控制器和操作方法去执行(你可以传入其他的参数),而后面的规则不会继续匹配

以上的路由配置说明:在每个路由表达式中,:后面跟参数名称,比如上面的:year,:month,:id都是参数名称,以:id为例,它指向Index控制器的read方法,这个方法接受一个$id的参数:

public function read($id){
    echo "read page with" .$id;
  }

Copy after login

在浏览器输入http://localhost:8999/index.php/Home/blogs/2就可以看到

read page with 2
Copy after login

Home就代表Home模块,你可以简单地将它映射到相应的Home目录,这是由于在默认的配置中

'DEFAULT_MODULE'    => 'Home'
Copy after login

你可以根据自己的需求修改,但本课依旧采用默认的Home模块.

如果你还需要传人额外的参数,像第一条的规则array('Index/archive', 'status=1')中的status一样传人,你看设置多个这样的参数。

如果你尝试在浏览器输入:

http://localhost:8999/index.php/Home/blogs/string

ThinkPHP也给我们返回了string,但在日常的开发中,我们通常需要限制:id变量是整数,那该怎么做呢?只需要稍稍改动就可以了,写成

'blogs/:id\d'        => 'Index/read',
Copy after login

以上\d表示限制变量id只能是数字。

对于可选参数,可以用[]包含表示,比如:

'blogs/:year/:month/[:day]' => array('Index/archive', 'status=1'),
Copy after login

上面的day现在就是可选参数了,你可以传人,也可以不传。

在ThinkPHP中,还支持在限制路由的后缀和使用正则路由。

限制路由后缀,通常使用在平时常见的html,htm等后缀,还是以上面的规则为例:

'blogs/:id'        => array('Index/read',array('ext'=>'html'))
Copy after login

你就可以限制这条规则只能在.html的路由后缀生效。

正则路由

正则本身就是一门很大的学问,在学习ThinkPHP的正则路由之前,最好是具备一定的正则表达式的基础。

路由表达式支持的正则定义必须以/开头,否则就视为规则表达式,比如:

'#^blog\/(\d+)$#' => 'Index/read'
Copy after login

这会解析为规则路由而不是正则路由,因为录音表达式并没有以/开始,所以,我们需要这样写:

'/^new\/(\d{4})\/(\d{2})$/' => 'Index/achive?year=:1&month=:2',
以上就是一条正确的正则路由。对于正则表达式中的每个正则规则子模式)部分(如\d{4}和\d{2}),如果需要在后面的路由地址中引用,可以采用:1、:2这样的方式,序号就是子模式的序号

静态路由

ThinkPHP框架其实还有一个路由机制叫静态路由,这实际上就是规则路由的静态简化版,路由定义中不包含动态参数(如上面的路由规则中id参数),静态路由不需要遍历路由规则而是直接定位,因此执行效率会较高。静态路由采用URL_MAP_RULES来定义规则:

'URL_ROUTER_ON'  => true,
'URL_MAP_RULES'=>array(
  'new/top' => 'Index/top?type=top'
)

Copy after login

由于Index/top?type=top中Index表示控制器,第一个top表示方法,所以我们需要在Index控制器中创建top方法:

public function top(){
    echo "top page </br>";
  }

Copy after login

根据上面这条规则,如果我们访问到

http://localhost:8999/index.php/Home/new/top

其实我们访问的是:

http://localhost:8999/index.php/Home/index/top/type/top
转译成就是new/top对应的是index控制器的top方法,传人的参数为type,参数值为top,所以就有了index/top/type/top

但是,当我们访问http://localhost:8999/index.php/Home/new/top/var/test尽管URL地址前面也有new/top,然而由于静态路由是完整匹配的性质,所以不会匹配到index/top/type/top

以上所述就是本文的全部内容了,希望大家能够喜欢。

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
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)

How to run thinkphp project How to run thinkphp project Apr 09, 2024 pm 05:33 PM

To run the ThinkPHP project, you need to: install Composer; use Composer to create the project; enter the project directory and execute php bin/console serve; visit http://localhost:8000 to view the welcome page.

There are several versions of thinkphp There are several versions of thinkphp Apr 09, 2024 pm 06:09 PM

ThinkPHP has multiple versions designed for different PHP versions. Major versions include 3.2, 5.0, 5.1, and 6.0, while minor versions are used to fix bugs and provide new features. The latest stable version is ThinkPHP 6.0.16. When choosing a version, consider the PHP version, feature requirements, and community support. It is recommended to use the latest stable version for best performance and support.

How to run thinkphp How to run thinkphp Apr 09, 2024 pm 05:39 PM

Steps to run ThinkPHP Framework locally: Download and unzip ThinkPHP Framework to a local directory. Create a virtual host (optional) pointing to the ThinkPHP root directory. Configure database connection parameters. Start the web server. Initialize the ThinkPHP application. Access the ThinkPHP application URL and run it.

How to install thinkphp How to install thinkphp Apr 09, 2024 pm 05:42 PM

ThinkPHP installation steps: Prepare PHP, Composer, and MySQL environments. Create projects using Composer. Install the ThinkPHP framework and dependencies. Configure database connection. Generate application code. Launch the application and visit http://localhost:8000.

Which one is better, laravel or thinkphp? Which one is better, laravel or thinkphp? Apr 09, 2024 pm 03:18 PM

Performance comparison of Laravel and ThinkPHP frameworks: ThinkPHP generally performs better than Laravel, focusing on optimization and caching. Laravel performs well, but for complex applications, ThinkPHP may be a better fit.

Java Apache Camel: Building a flexible and efficient service-oriented architecture Java Apache Camel: Building a flexible and efficient service-oriented architecture Feb 19, 2024 pm 04:12 PM

Apache Camel is an Enterprise Service Bus (ESB)-based integration framework that can easily integrate disparate applications, services, and data sources to automate complex business processes. ApacheCamel uses route-based configuration to easily define and manage integration processes. Key features of ApacheCamel include: Flexibility: ApacheCamel can be easily integrated with a variety of applications, services, and data sources. It supports multiple protocols, including HTTP, JMS, SOAP, FTP, etc. Efficiency: ApacheCamel is very efficient, it can handle a large number of messages. It uses an asynchronous messaging mechanism, which improves performance. Expandable

How is the performance of thinkphp? How is the performance of thinkphp? Apr 09, 2024 pm 05:24 PM

ThinkPHP is a high-performance PHP framework with advantages such as caching mechanism, code optimization, parallel processing and database optimization. Official performance tests show that it can handle more than 10,000 requests per second and is widely used in large-scale websites and enterprise systems such as JD.com and Ctrip in actual applications.

Where is the thinkphp homepage file? Where is the thinkphp homepage file? Apr 09, 2024 pm 05:54 PM

The homepage file in the ThinkPHP framework is used to define the homepage of the website. It is located at app/home/controller/IndexController.php and contains an action method named index, which is responsible for processing homepage requests. This method contains the business logic of the homepage and returns the view file app/home/view/index/index.html.

See all articles