- ThinkPHP 5实战
- 夏磊
- 435字
- 2025-02-23 15:38:02
2.4 配置的读写与示例
使用配置的最终目的是方便开发,也就是在合适的时候需要读写配置,比如实例化数据库的时候需要读取database配置。ThinkPHP通过Config::get和Config::set读写配置。
下面我们来看配置的一个示例,这个示例将完成以下内容的验证:
- 惯例配置的加载
- 全局配置的加载
- 扩展配置的加载
- 场景配置的加载
- 模块配置的加载
- 动态配置的加载与读写
步骤说明如下:
(1)解压缩ThinkPHP 5核心版。
(2)运行PHP服务器,启动命令参照1.2节的相关内容。(3)编辑application/index/controller/Index.php:

(4)访问http://localhost:8080,可以看到输出了一段JSON,这就是ThinkPHP的默认配置(惯例配置)。
(5)新建application/extra/amqp.php文件(如果extra目录不存在,就手动创建)。

(6)刷新页面,可以看到有刚才配置的amqp配置。
(7)将application/config.php的app_status更改为home。
(8)添加application/home.php。

(9)刷新页面,可以看到amqp的输出已经变成home.php中定义的内容。
(10)添加application/index/config.php。

(11)刷新页面,发现amqp又发生了变化,与上面定义的文件一致。
(12)添加application/index/home.php。

(13)继续刷新页面,发现amqp又发生了变化,与上面定义的文件一致。
(14)编辑application/index/controller/Index.php,添加rw方法测试配置的读写。

(15)访问http://localhost:8080/index/index/rw,可以看到如下输出:
NULL string(3) "111"