ThinkPHP6在默认的单应用下,做接口:增加控制器、方法、查询参数,定义路由,返回JSON数据

发布时间:2025-04-02      访问量:94
环境:
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"}
堆内存
多线程
strdup
初始化器
冒泡排序
增删改查
BufferedReader
输入输出
面向对象
生命周期
闭包的概念
原型链
Flask
mysql-connector-python
单例模式
浅拷贝
隔离级别
索引
InnoDB
左连接
聚合函数
PuTTY
TRUNCATE
str_starts_with_many
DateTime
array_combine
闭包的概念