model(['id' => 'id'])"."/> model(['id' => 'id'])".">
Home > Article > Backend Development > What are the methods for modifying routing in thinkphp?
There are two ways to modify routes in thinkphp: 1. Use the rule() method in the route.php file to directly modify the news route into an article route. The code is "rule('article','index/News /index')"; 2. Dynamically define routing rules in the controller, the code is "rule('news/:id', 'index/News/read')->model(['id' => ' id'])".
The operating system for this tutorial: Windows 10 system, thinkphp6.1.2 version, Dell G3 computer.
In thinkphp, we can customize the URL address and dispatch it to the corresponding controller method by defining routing rules.
To modify routing rules, there are two methods:
1. Modify directly in the route.php file, which is located in the project directory. /route directory.
The following is a sample code, in which we modify the news route into the article route:
<?php use think\Route; // 修改/news路由规则为/article Route::rule('article','index/News/index');
The above code calls the rule() method provided by ThinkPHP, and Pass the route URL and parameters to the controller method. Note:
The first parameter represents the routing URL address suffix, such as article here.
The second parameter indicates the path of the controller pointed by the route, for example, it points to index/News/index.
#2. Dynamically define routing rules in the controller. This method is usually used to dynamically generate routing rules based on changes when the program is running.
The following is a sample code in which routing rules are dynamically generated by defining a closure function:
<?php namespace app\index\controller; use think\Route; class Index { public function index() { // 动态生成路由规则 Route::rule('news/:id', 'index/News/read')->model(['id' => 'id']); return "动态路由规则生成成功"; } }
The above code will dynamically generate the index method when accessing the index method of the Index controller. Map the news/:id routing rule to the index/News/read controller method, and use model binding to automatically generate SQL query statements when binding parameters.
The above is the detailed content of What are the methods for modifying routing in thinkphp?. For more information, please follow other related articles on the PHP Chinese website!