ThinkPHP6,使用默认的单应用,/config/route.php中的强制使用路由的参数url_route_must为false。
增加控制器和方法:
在/app/controller/下新建文件 Test.php,写入下边一段程序,其实就是从别的控制器复制过来的:
namespace app\controller;
use app\BaseController;
class Test extends BaseController{
public function index(){
return 'I am Test index.';
}
public function hello($id,$name='zhangsan'){
$data['id']=$id;
$data['name']=$name;
return json($data);
}
}
浏览器访问:
(host)/test/index,结果:
I am Test index.
(host)/test,也会正常显示结果:(这里可以正常显示,是因为/config/route.php中的default_action默认为index。)
I am Test index.
(host)/test/hello/id/1,结果:(这里没有name参数也可以,因为hello方法中,$name有默认值。)
{"id":"1","name":"zhangsan"}
(host)/test/hello/id/2/name/lisi,结果:
{"id":"2","name":"lisi"}
设置路由:
如果强制使用路由的参数url_route_must为false,默认就是false,那么上边的工作就已经完成了。
如果url_route_must为true,就需要设置对应的路由才可以访问:
Route::get('test_index', 'test/index');
Route::get('test_hello/:id/[:name]', 'test/hello');
浏览器访问:
(host)/test_index,结果:
I am Test index.
(host)/test_hello/1,结果:(这个可以显示,是因为上边的路由规则中,name参数是可选的。)
{"id":"1","name":"zhangsan"}
(host)/test_hello/1/zhangsan,结果:
{"id":"1","name":"zhangsan"}